Windows Phone 72012. 3. 13. 20:03

예전에 DataTemplateSelector라는거에 대해서 포스트 했었다.

그건 보여주는것에 대해서 DataTemplate을 유동적으로 바꾸는것이였다.

하지만 이번에 할것은 어떤 특정한 이벤트 예를 들어 ListBox의 Item에 버튼을 클릭하면 해당셀의 TextBlock이 수정할수 있는

TextBox로 변하게 한다등등 셀의 DateTemplate을 마음대로 변경할수 있다.

일단 listbox를 만든다. 하지만 난 여기서 ReorderListbox를 이용했음으로 reorderlistbox로 설명하겠다.

 <ct:ReorderListBox x:Name="listBox" Grid.Row="1" ItemsSource="{Binding Data}" Foreground="{StaticResource PhoneForegroundBrush}" IsReorderEnabled="True" ItemTemplate="{StaticResource MyAlbumDataTemplate}">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectionChanged">
                    <i:Interaction.Behaviors>
                        <ec:ConditionBehavior>
                            <ec:ConditionalExpression>
                                <ec:ComparisonCondition LeftOperand="{Binding SelectedIndex, ElementName=listBox}" Operator="NotEqual" RightOperand="-1"/>
                            </ec:ConditionalExpression>
                        </ec:ConditionBehavior>
                    </i:Interaction.Behaviors>
                    <i:InvokeCommandAction Command="{Binding SelectAlbumCommand}" CommandParameter="{Binding SelectedItem, ElementName=listBox}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </ct:ReorderListBox>

아래 selectChanged 이벤트는 무시해도 된다. 하지만 대부분 behind에서 하는 이벤트 처리를 xaml에서 하게 할수 있다(보너스)

 

그리고 리소스를 등록한다.

 

 <UserControl.Resources>
        <DataTemplate x:Key="TextBoxDataTemplate">
                <Grid d:DesignWidth="385" d:DesignHeight="100" Height="80" Margin="0,0,0,10">
                    <Button Content="R" x:Name="RenameButton" Click="RenameButton_Click" Grid.Column="1" >
                        <tk:ContextMenuService.ContextMenu>
                            <tk:ContextMenu>
                                <tk:MenuItem Header="변경" Click="RenameButton_Click"/>
                            </tk:ContextMenu>
                        </tk:ContextMenuService.ContextMenu>
                    </Button>

머 이렇식으로 시작해서 만들자 각각 다른것을 2개를 만들어야 한다. 한개는 일반꺼 한개는 클릭했을때 나오는 dataTempalate

 

자이제 DateTemplate 안에 클릭했을때 itemTemplate을 변경해보자

private void RenameButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            (listBox.ItemContainerGenerator.ContainerFromItem((sender as Button).DataContext as MyAlbum) as ReorderListBoxItem).ContentTemplate = this.Resources["TextBoxDataTemplate"] as DataTemplate;
            //(listBox.ItemContainerGenerator.ContainerFromIndex(0) as ListBoxItem).ContentTemplate = this.Resources["TextBoxDataTemplate"] as DataTemplate;
        }

 

아래는 index로도 바꿀수 있다는 예시를 했다. 이렇게 하면 해당셀의 ContentTemplate을 얻어올수 있고 직접 넣을수 있다.

 

참고 : http://stackoverflow.com/questions/329556/focus-on-a-textbox-in-a-datatemplate

Posted by 동동(이재동)
Windows Phone 72012. 2. 15. 09:49

Toolkit에서 제공하는 LongListSelector를 이용해서 만들었고

주의할점은 binding 할때 무조건 그룹쪽은 Title로 해야 한다. 

자세한설명은 소스보면 알듯

이건 테스트로 만든것이고 실제는 코레일에 예쁘게 잘만들어놓았다..


Posted by 동동(이재동)
Windows Phone 72012. 1. 18. 10:27

<ListBoxx:Name="ReturnTicketListBox" ItemsSource="{BindingItemSource}"Grid.Row="3"ScrollViewer.VerticalScrollBarVisibility="Hidden">
                <
ListBox.ItemTemplate>
                    <
DataTemplate>
                        <
GridHeight="87"Width="480">
                            <
Grid.ColumnDefinitions>
                                <
ColumnDefinitionWidth="148"/>
                                <
ColumnDefinitionWidth="92"/>
                                <
ColumnDefinitionWidth="80"/>
                                <
ColumnDefinitionWidth="79"/>
                            </
Grid.ColumnDefinitions>
                            <
CheckBoxIsChecked="{BindingIsChecked,Mode=TwoWay}"/>
                            <
StackPanelOrientation="Horizontal" Grid.Column="1">
                                <
TextBlockText="{Bindingh_srcar_no}"HorizontalAlignment="Center"VerticalAlignment="Center"Foreground="Black" />
                                <
TextBlockText="{Bindingh_seat_no}"HorizontalAlignment="Center"VerticalAlignment="Center"Foreground="Black" />
                            </
StackPanel>
                            <
TextBlockText="{Bindingh_ret_amt,Converter={StaticResourceMoneyConveter}}"HorizontalAlignment="Center"Grid.Column="2"VerticalAlignment="Center"Foreground="Black" />
                            <
TextBlockText="{Bindingh_ret_fee,Converter={StaticResourceMoneyConveter}}"HorizontalAlignment="Center"Grid.Column="3"VerticalAlignment="Center"Foreground="Black" />
                        </
Grid>
                    </
DataTemplate>
                </
ListBox.ItemTemplate>
            </
ListBox>

 

이렇게 itemsource를 넣고 checkbox를 twoway로 한다

<CheckBox IsChecked="{Binding IsChecked, Mode=TwoWay}"/>

public class ReturnTicketModel
    {       
        public string Test { get; set; }

        public bool IsChecked { get; set; }
    }

 

모델은 그냥 이렇게 하면 된다.

너무 쉬운 부분이지만 모르는 사람은 답답할 수도 있고 code behind에서 이벤트 받아서 하는 초보적인 방법으로

할수도 있어서 포스팅 해본다.

Posted by 동동(이재동)
Windows Phone 72011. 12. 28. 14:22

보통 리스트 박스에 스타일을 입히기 위해서

<ListBox.ItemTemplate>
  <
DataTemplate>

이런게 DataTemplate 을 한다.

하지만 여기서 Select 했을때 특정 컨트롤 색을 바꾸고 싶거나 배경을 없애거나 머 이렇게 하고 싶었다.

블랜드로 하는게 편할거다.

ListBox에서 오른쪽 버튼을 눌러서 ItemContainerStyle을 선택후 edit/copy를 한후

코드에서 selected와 unselected코드 부분을 지웠다.(있어봤자 필요도 없음 어짜피 새로 만들꺼니)

그리고 기본적으로 포함 되어 있는 ContentControl 도 지웠다.

그리고 DataTemplate안에 있는 내용을 그대로 contentControl 를 지운부분에 삽입했다.

최종 xaml 코드이다.

<phone:PhoneApplicationPage.Resources>
        <Style x:Key="ListBoxItemStyle1" TargetType="ListBoxItem">
            <Setter Property="Background" Value="Transparent"/>
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="BorderBrush" Value="Transparent"/>
            <Setter Property="Padding" Value="0"/>
            <Setter Property="HorizontalContentAlignment" Value="Left"/>
            <Setter Property="VerticalContentAlignment" Value="Top"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <Border x:Name="LayoutRoot" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}">
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                    <VisualState x:Name="Normal"/>
                                    <VisualState x:Name="MouseOver"/>
                                    <VisualState x:Name="Disabled">
                                    </VisualState>
                                </VisualStateGroup>
                                <VisualStateGroup x:Name="SelectionStates">
                                    <VisualState x:Name="Unselected"/>
                                    <VisualState x:Name="Selected">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="image">
                                                <DiscreteObjectKeyFrame KeyTime="0">
                                                    <DiscreteObjectKeyFrame.Value>
                                                        <Visibility>Collapsed</Visibility>
                                                    </DiscreteObjectKeyFrame.Value>
                                                </DiscreteObjectKeyFrame>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>
                            <!--<ContentControl x:Name="ContentContainer" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>-->
                            <Grid Height="106" Width="166">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="126"/>
                                    <ColumnDefinition/>
                                </Grid.ColumnDefinitions>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="40"/>
                                    <RowDefinition/>
                                </Grid.RowDefinitions>
                                <Image Source="/GloryApp;component/Images/Ticket_GroupItem_Nor@2x.png" Stretch="Fill" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="151" Height="96" Grid.RowSpan="2" Grid.ColumnSpan="2"/>
                                <Image Grid.ColumnSpan="2" Grid.RowSpan="2" Source="/GloryApp;component/Images/Ticket_GroupItem_Sel@2x.png" Stretch="Fill" Width="151" Height="96" HorizontalAlignment="Left" VerticalAlignment="Bottom"/>
                                <Image Source="/GloryApp;component/Images/Ticket_GroupItem_Badge_Green@2x.png" Stretch="Fill" Width="40" Height="40" Grid.Column="1" d:IsHidden="True"/>
                                <Image x:Name="image" Source="/GloryApp;component/Images/Ticket_GroupItem_Badge_Red@2x.png" Stretch="Fill" Width="40" Height="40" Grid.Column="1"/>
                                <TextBlock Text="{Binding TicketCount}" Grid.ColumnSpan="2" VerticalAlignment="Center" FontFamily="Malgun Gothic" Grid.Column="1" HorizontalAlignment="Center" FontSize="22.667" Margin="0,0,0,4" Foreground="White" />
                                <Grid Grid.ColumnSpan="2" Grid.RowSpan="2" d:DesignWidth="183" d:DesignHeight="180" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="151" Height="96" >
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="34"/>
                                        <RowDefinition Height="24"/>
                                        <RowDefinition Height="27"/>
                                        <RowDefinition/>
                                    </Grid.RowDefinitions>
                                    <TextBlock Text="{Binding h_dpt_dt}" VerticalAlignment="Bottom" HorizontalAlignment="Center" Foreground="Black" FontFamily="Malgun Gothic" />
                                    <StackPanel Orientation="Horizontal" d:LayoutOverrides="Height" Grid.Row="1" HorizontalAlignment="Center">
                                        <TextBlock Text="{Binding h_dpt_tm}" Foreground="Black" FontFamily="Malgun Gothic" FontSize="18.667" />
                                        <TextBlock Text="출발" Foreground="Black" FontFamily="Malgun Gothic" FontSize="18.667" />
                                    </StackPanel>
                                    <StackPanel Orientation="Horizontal" VerticalAlignment="Top" Grid.Row="2" d:LayoutOverrides="VerticalAlignment" HorizontalAlignment="Center">
                                        <TextBlock Text="{Binding h_dpt_rs_stn_nm}" Foreground="Black" FontSize="18.667" FontFamily="Malgun Gothic" />
                                        <TextBlock Text="&gt;" Foreground="Black" FontSize="18.667" FontFamily="Malgun Gothic" />
                                        <TextBlock Text="{Binding h_arv_rs_stn_nm}" Foreground="Black" FontSize="18.667" FontFamily="Malgun Gothic" />
                                    </StackPanel>
                                </Grid>
                            </Grid>

                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </phone:PhoneApplicationPage.Resources>

보면 contentControl 대신 dataTemplate에 있는걸 넣었다. 그냥

그뒤 블랜드로 Status를 Selected로 해서 선택했을때에 맞게 조정하면 되는것이다.

Posted by 동동(이재동)
Windows Phone 72011. 12. 22. 10:58

WPF에서는 DataTemplateSelector가 기본적으로 제공되지만 윈폰은 없다 ㅡ.ㅡ;;

하지만 만들면 된다.

namespace GloryApp.Utils
{
    public abstract class DataTemplateSelector : ContentControl
    {
        public virtual DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            return null;
        }

        protected override void OnContentChanged(object oldContent, object newContent)
        {
            base.OnContentChanged(oldContent, newContent);

            ContentTemplate = SelectTemplate(newContent, this);
        }
    }
}

이렇게 DataTemplateSelcotr class를 만들고

namespace GloryApp.Utils
{
    public class ReserveTypeSelecter : DataTemplateSelector
    {
        public DataTemplate GeneralTrain { get; set; }

        public DataTemplate TransferTrain { get; set; }

        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            //var data = item as JrnyInfoModel;

            if (item == GeneralTrain)
            {
                return GeneralTrain;
            }
            else
            {
                return TransferTrain;
            }

            return base.SelectTemplate(item, container);
        }
    }
}

 

이렇게 사용할 Selector를 하나만들고 SelectTemplate 메소드 안에서 자기가 원하는 DataTemplate를 선택해서 return 할수 있다.

<ListBox x:Name="ReserveListBox" ItemsSource="{Binding ResultViewData}" Grid.Row="1" >             
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <st:ReserveTypeSelecter Content="{Binding}">
                            <st:ReserveTypeSelecter.GeneralTrain>
                                <DataTemplate>
                                    <Grid>
                                        <StackPanel Orientation="Horizontal">
                                            <TextBlock Text="{Binding h_run_dt, Converter={StaticResource ShortDateFormatWithWeekConverter}}" Foreground="White"  Margin="10,0,10,0"/>
                                            <StackPanel Margin="10,0,10,0" Width="50">
                                                <TextBlock Text="{Binding h_trn_clsf_cd, Converter={StaticResource TrainNameConverter}}" Foreground="White" />
                                                <TextBlock Text="{Binding h_trn_no}" Foreground="White" />
                                            </StackPanel>
                                            <StackPanel Margin="10,0,10,0" Width="50" >
                                                <TextBlock Text="{Binding h_dpt_rs_stn_nm}" Foreground="White" />
                                                <TextBlock Text="{Binding h_dpt_tm, Converter={StaticResource StringShortTimeConverter}}" Foreground="White" />
                                            </StackPanel>
                                            <StackPanel Margin="10,0,10,0" Width="50">
                                                <TextBlock Text="{Binding h_arv_rs_stn_nm}" Foreground="White" />
                                                <TextBlock Text="{Binding h_arv_tm, Converter={StaticResource StringShortTimeConverter}}" Foreground="White" />
                                            </StackPanel>
                                            <TextBlock Text="{Binding LimitDate}" Foreground="red"  Margin="10,0,10,0"/>
                                        </StackPanel>
                                    </Grid>
                                </DataTemplate>
                            </st:ReserveTypeSelecter.GeneralTrain>
                            <st:ReserveTypeSelecter.TransferTrain>
                                <DataTemplate>
                                    <Grid>
                                        <StackPanel Orientation="Horizontal">
                                            <TextBlock Text="{Binding h_run_dt, Converter={StaticResource ShortDateFormatWithWeekConverter}}" Foreground="White"  Margin="10,0,10,0"/>
                                            <StackPanel Margin="10,0,10,0" Width="50">
                                                <TextBlock Text="{Binding h_trn_clsf_cd, Converter={StaticResource TrainNameConverter}}" Foreground="White" />
                                                <TextBlock Text="{Binding h_trn_no}" Foreground="White" />
                                            </StackPanel>
                                            <StackPanel Margin="10,0,10,0" Width="50" >
                                                <TextBlock Text="{Binding h_dpt_rs_stn_nm}" Foreground="White" />
                                                <TextBlock Text="{Binding h_dpt_tm, Converter={StaticResource StringShortTimeConverter}}" Foreground="White" />
                                            </StackPanel>
                                        </StackPanel>
                                    </Grid>
                                </DataTemplate>
                            </st:ReserveTypeSelecter.TransferTrain>
                        </st:ReserveTypeSelecter>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

이제 xaml에서는 이렇게 2개의 DataTemplate을 넣어준다.

그래서 선택할수 있다.

참조 : http://windowsphonegeek.com/articles/Implementing-Windows-Phone-7-DataTemplateSelector-and-CustomDataTemplateSelector

소스 :

Posted by 동동(이재동)
Windows Phone 72011. 3. 21. 18:36

지금까지 UserControl만 주구장창 만들어보았으면

 

이번에는 Control을 만들어서 dll로 빼서 편리하게 사용해보자.

 

첨에는 프로젝트를 라이브러리 프로젝트로 하나 만든다.

 

그리고 일단 UI가 있는것은 스타일이 필요할테니 Theme 폴더안에 generic.xaml을 만들자

 

그리고 이렇게 입력하자

 

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
    xmlns:system="clr-namespace:System;assembly=mscorlib"
    xmlns:c="clr-namespace:AboutPageControlLibrary"    
    xmlns:sys="clr-namespace:System.Windows;assembly=System.Windows" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d">
    <Style TargetType="c:AboutPageControl">
        
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="c:AboutPageControl">                    
                    <Grid>
                        <ListBox x:Name="AppListBox"  Margin="30,0,0,0" />
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        

 

이렇게 해서 AboutPageControl을 만들고 그안에 단순히 ListBox만 하나 넣었다. x:name은 ApplistBox로 정했다.

 

자 이제

 

cs파일을 하나 만드는데 Control을 상속받자

 

public class AboutPageControl : Control

 

그리고 생성자를 만든다.

public AboutPageControl()
       {
           DefaultStyleKey = typeof(AboutPageControl);

 

이렇게 DefaultStylekey로 하여서 아까 generic.xaml에 정의된 스타일을 가져온다.

 

자 이렇게만 하고 프로젝트 하나 만들어서 여기 dll을 참조 한후 사용하면

 

ListBox가 보일것이다.(사실은 아무것도 안보일껏이다 itemSource가 없으니^^)

 

자 그럼 이제 Listbox에 ItemSource를 정의해보자.

 

일단 저기 generic.xaml에 정의한 스타일의 컨트롤을 호출을 해야 한다.

 

public override void OnApplyTemplate()
       {
           base.OnApplyTemplate();
           this._listBoxControl = GetTemplateChild("AppListBox") as ListBox;
       }

 

이렇게 OnApplyTemplate를 오버라이드 한후

 

GetTemplateChild를 이용해서 Listbox를 _ListBoxControl에 정의하였다. _listBoxControl은 전역변수에 이미 정의를 했다이로써 언제든지 ListBox를 쓸수 있게 되었다.

 

그후에 이제 이 Listbox Itemsource에 data를 넣어보자.

 

public AboutPageControl()
       {
           DefaultStyleKey = typeof(AboutPageControl);
           this.Loaded += new RoutedEventHandler(AboutPageControl_Loaded);
       }

 

loaded에 넣은 이유는 알것이다.

 

 

void AboutPageControl_Loaded(object sender, RoutedEventArgs e)
        {
            List<AppData> appDatas = new List<AppData>();
            appDatas.Add(new AppData() { Id = "App1", Name = "himan2", Description = "haha" });
            appDatas.Add(new AppData() { Id = "App1", Name = "himan2", Description = "haha" });
 
            _listBoxControl.ItemsSource = appDatas;
            _listBoxControl.ItemTemplate = ItemTemplate;

 

이렇게 itemsource를 넣었다.

 

그러면 이제 itemSource도 보일것이다. 근데 또 궁금증이 있다. itemTemplate은 어떻게 줄것인가?

Control이 아니라면 그냥 xaml상에서도 줄수 있지만 여기서 이렇게 behind로 해야만 했다.

저위에 정의 되어 있는 ItemTemplate은 이렇게 정의 해줘야 한다. 미리

 

public DataTemplate ItemTemplate
      {
          get { return (DataTemplate)GetValue(ItemTemplateProperty); }
          set { SetValue(ItemTemplateProperty, value); }
      }
 
      public static readonly DependencyProperty ItemTemplateProperty =
          DependencyProperty.Register("ItemTemplate", typeof(DataTemplate), typeof(AboutPageControl), new PropertyMetadata(OnItemTemplateChanged));
 
      protected static void OnItemTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
      {
      }

 

사실 OnItemTemplateChanged는 의미가 없는듯 ;;

 

이렇게 정의 해두고 generic.xaml 에

 

<Setter Property="ItemTemplate" >            
           <Setter.Value>                
               <DataTemplate>
                   <Grid x:Name="grid">
                       <Grid.Resources>
                           <c:FileNameToFilePathImageConverter x:Name="FTFConverter" />
                       </Grid.Resources>
                       <Grid.ColumnDefinitions>
                           <ColumnDefinition Width="100" />
                           <ColumnDefinition />
                       </Grid.ColumnDefinitions>
                       <Grid.RowDefinitions >
                           <RowDefinition />
                           <RowDefinition />
                       </Grid.RowDefinitions>
                       <Image x:Name="image" Source="{Binding iconFileName, Converter={StaticResource FTFConverter}}"  Grid.RowSpan="2" Width="99" Height="99"/>
                       <TextBlock x:Name="textBlock" Text="{Binding Name}" Grid.Column="1" FontWeight="Bold" Margin="20,0,0,0"/>
                       <TextBlock Text="{Binding Description}" Grid.Column="1" Grid.Row="1" FontSize="16" Margin="20,0,0,0" TextWrapping="Wrap" />
                   </Grid>
               </DataTemplate>
       </Setter.Value>
       </Setter>

 

이렇게 Property에 이름을 ItemTemplate로 정의 한다면

 

ListBox에 ItemTemplate이 정의가 되어서 아주 멋있는 ListBox가 보여질것이다. 이미지와 글이 있는^^

 

이제 어떻게 컨트롤을 처음에 만들고 Listbox를 추가하며 그안에 itemSouce와 ItemTemplate을 정의 하는지 알려주었다

Posted by 동동(이재동)