티스토리 뷰

반응형

1. Dispatcher

 

private Windows.UI.Core.CoreDispatcher dispatcher = Window.Current.CoreWindow.Dispatcher;

 

await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
    () =>
    {
        if (task.IsFaulted)
        {
            //Console.WriteLine("Send failed {0}", task.Exception.GetBaseException());
            var fail = string.Format("Send failed {0}", task.Exception.GetBaseException());
            StringCollection.Insert(0, fail);
        }
        else
        {
            //Console.WriteLine("Success");
            var success = "Success";
            StringCollection.Insert(0, success);
        }
    });

 

4. GridView 내부 아이템 높이 맞추기

화면 해상도가 달라지면 아이템들의 높이가 달라져서 높낮이가 달라 보이는 경우

 

        public void SizeChanged(object sender, SizeChangedEventArgs e)
        {
            GridItemHeight = e.NewSize.Height;
        }

그리드 메인 뷰 모델에서 그리드뷰의 사이즈 변경 이벤트에서 높이를 받고

 

<Grid MinHeight="{Binding MainVM.GridItemHeight, Source={StaticResource Locator}}">

....

각 아이템 내부 그리드의 최소 높이를 바인딩 시켜 준다.

더 좋은 방법이 있으면 좋은데..지금은 이게 최선의 방법이라는..

 

2. Delay

await Task.Delay(TimeSpan.FromSeconds(1));

 

 

3. GridView in GridView Template

그리드뷰 내부에 그리드뷰가 들어갈때 마우스 휠이 동작하도록 만든 템플릿

 

    <Style x:Key="GridViewInGridViewStyle" TargetType="GridView">
        <Setter Property="Padding" Value="0,0,0,10"/>
        <Setter Property="IsTabStop" Value="False"/>
        <Setter Property="TabNavigation" Value="Once"/>
        <Setter Property="IsSwipeEnabled" Value="True"/>
        <Setter Property="ItemContainerTransitions">
            <Setter.Value>
                <TransitionCollection>
                    <AddDeleteThemeTransition/>
                    <ContentThemeTransition/>
                    <ReorderThemeTransition/>
                    <EntranceThemeTransition IsStaggeringEnabled="False"/>
                </TransitionCollection>
            </Setter.Value>
        </Setter>
        <Setter Property="ItemsPanel">
            <Setter.Value>
                <ItemsPanelTemplate>
                    <WrapGrid Orientation="Vertical"/>
                </ItemsPanelTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="GridView">
                    <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}">
                        <ItemsPresenter HeaderTemplate="{TemplateBinding HeaderTemplate}" Header="{TemplateBinding Header}" HeaderTransitions="{TemplateBinding HeaderTransitions}" Padding="{TemplateBinding Padding}"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

 

5. Uri를 이용해서 파일을 다운로드 받아서 앱 임시 폴더에 저장

 

        private async Task<bool> DownloadFile(string downloadUri, string fileName)
        {
            Stream downloadStream;
            using (HttpClient hc = new HttpClient())
            {
                downloadStream = await hc.GetStreamAsync(new Uri(downloadUri));
                if (downloadStream == null) return false;
            }
            StorageFile file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
            using (Stream fileStream = await file.OpenStreamForWriteAsync())
            {
                await downloadStream.CopyToAsync(fileStream);
                await fileStream.FlushAsync();
                downloadStream.Dispose();
            }
            return true;
        }

 

6. 임시폴더의 파일 내용을 String으로 반환 - 한글 처리

 

//buffer.ToArray()를 사용하기 위해 반드시 필요

using System.Runtime.InteropServices.WindowsRuntime;

 

        private async Task<string> FileToString(string fileName)
        {
            StorageFile file = await ApplicationData.Current.TemporaryFolder.GetFileAsync(fileName);
            IBuffer buffer = await FileIO.ReadBufferAsync(file);
            byte[] fileData = buffer.ToArray();
            Encoding encoding = Encoding.GetEncoding("euc-KR");
            string data = encoding.GetString(fileData, 0, fileData.Length);
            return data;
        }

 

7. "20121113"을 DateTime으로 변환

var dt = DateTime.Parse(string.Format("{0:####-##-##}", Convert.ToInt16("20121113")));

 

8. DateTime을 TotalMilliseconds로 변환

var tMilli = Convert.ToInt64(TimeSpan.FromTicks(DateTime.Now.Ticks).TotalMilliseconds);

 

9. Uri Check

    Uri uri;
    if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out uri))
    {
        rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
        return;
    }

 

10. Snap 모드 확인

    // Verify that we are currently not snapped, or that we can unsnap to open the picker.
    if (ApplicationView.Value == ApplicationViewState.Snapped && !ApplicationView.TryUnsnap())
    {
        rootPage.NotifyUser("File picker cannot be opened in snapped mode. Please unsnap first.", NotifyType.ErrorMessage);
        return;
    }

 

11. GridView 아이템들의 높이 동일하게 만들기

    <ItemsPanelTemplate x:Key="MainViewItemsPanelTemplate">
        <StackPanel Orientation="Horizontal" VerticalAlignment="Stretch"/>
    </ItemsPanelTemplate>

 

ItemContainerStyle에서 아래 부분 수정

ContentPresenter x:Name="contentPresenter" ContentTransitions="{TemplateBinding ContentTransitions}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}"/>

 

12. 컬렉션 데이터를 대분류, 중분류로 나누어 주는 LINQ

var cate1 = from kkk in SkySearchCodeCollection
             where kkk.ParentID == 1
             let head = new CategoryModel { Category = kkk }
             join jjj in SkySearchCodeCollection
             on kkk.MSTID equals jjj.ParentID
             let detail = new SubCategoryModel{ SubCategory = jjj }
             select new { Head = head,  Detail = detail};

 

foreach (var item in cate1)
{
    if (CategoryCollection.Count(p => p.Category.MSTID == item.Head.Category.MSTID) == 0)
    {
        CategoryCollection.Add(item.Head);
    }
    item.Head.SubCategorys.Add(item.Detail);
}

 

13. AppBar - IsSticky

IsOpen과 IsSticky를 동시에 사용할 때 순서가 중요 IsSticky를 먼저 써준다. 아마 다른 컨트롤들도 그런것이 있을지도..

 

        <AppBar x:Name="BottomAppBar" Padding="10,0,10,0" IsSticky="{Binding IsSelected}" IsOpen="{Binding IsSelected, Mode=TwoWay}" >
            <AppBar.Background>
                <ImageBrush ImageSource="ms-appx:///Assets/res/app_bar_bg.png"/>
            </AppBar.Background>
            <Grid>
                <StackPanel x:Name="RightPanel" Orientation="Horizontal" HorizontalAlignment="Right">
                </StackPanel>
            </Grid>
        </AppBar>

 

14. String to Enum

문자열로 받은 데이터를 Enum형태로 변환한다.

toStop, toStart가 문자열임

 

Movement whereToStop = (Movement)Enum.Parse(typeof(Movement), toStop);
Movement whereToStart = (Movement)Enum.Parse(typeof(Movement), toStart);

 

15. 문자열 Type을 Assembly에서 찾기

Class Library에서 문자열로 받은 Type을 찾아야 할 경우 사용

 

string findTypeName = "App1.SecondPage";

var t = Windows.UI.Xaml.Application.Current.GetType().GetTypeInfo().Assembly.GetType(findTypeName);

 

16. GridView, ListView ItemClick 이벤트를 인터렉션 커맨드로 사용해서 넘길때 아규먼트 넘기기

http://marcominerva.wordpress.com/2013/03/07/how-to-bind-the-itemclick-event-to-a-command-and-pass-the-clicked-item-to-it/

 

<
GridView
    x:Name="itemGridView"
    ...>
    <triggers:Interactions.Triggers>
        <triggers:EventTrigger EventName="ItemClick">
            <triggers:InvokeCommandAction Command="{Binding MyItemClickCommand}"
                                          PassEventArgsToCommand="True" />
        </triggers:EventTrigger>
    </triggers:Interactions.Triggers>
 
</GridView>

 

17. 현재 윈도우의 크기(해상도)

var rect = Windows.UI.Xaml.Window.Current.Bounds;

 

18. Object형 데이터에서 특정 프로퍼티로 데이터를 끄집어 내서 Type로 변환해서 리턴

 

PCL

        /// <summary>
        /// 오브젝트 내부의 프로퍼티 데이터를 반환
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public abstract T GetPropertyValue<T>(object source, string propertyName) where T : class;

 

Windows 8 Morden app, Class Library

 

        public override T GetPropertyValue<T>(object source, string propertyName)
        {
            T returnValue = default(T);
            var pinfo = source.GetType().GetRuntimeProperty(propertyName);
            if (pinfo != null)
            {
                object[] indexArgs = {};
                var result = pinfo.GetValue(source);
                if (result != null)
                {
                    returnValue = (T)result;
                }
            }
            return returnValue;
        }

 

반응형

'Previous Platforms > ETC' 카테고리의 다른 글

Windows 8 Store app registing  (0) 2012.10.26
Portable Class Library Tips  (0) 2012.09.19
Metro style app data save in app local folder - Windows 8 RP  (0) 2012.07.31
Windows 8 Metro app links  (0) 2012.06.12
Tips - install 3.5  (0) 2012.05.17
댓글