ChiaFong

To bind or not to bind (Part 2)

In Programming on 25 July, 2008 at 7:00 am

To expand on what I’ve mentioned in my previous post.  The list box declared in XAML will look something like this:

<ListBox
    x:Name="CheckList"
    ItemTemplate="{DynamicResource CheckListTemplate}"
    ItemsSource="{Binding Source={StaticResource CheckedSource},
                  Mode=Default}">
</ListBox>

Under the <Windows.Resources>, the data template will be declared as:

<DataTemplate x:Key="CheckListTemplate">
  <StackPanel Margin="0,3,0,2" Orientation="Horizontal">
    <CheckBox IsChecked="{Binding Path=IsShown}"/>
    <TextBlock Text="{Binding Path=Name}"/>
  </StackPanel>
</DataTemplate>

At the same place or inside a style XAML’s ResourceDictionary, the data source is declared as:

<source:SColorList x:Key="CheckedSource"/>

Inside the C# file the classes are declared as:

    public class SColor : INotifyPropertyChanged
    {
        private string displayName;
        private Color clrShow;
        private bool permanent;
        private bool show;
 
        public bool IsShown
        {
            set
            {
                show = value;
                OnPropertyChanged("IsShown");
            }
            get
            {
                return show;
            }
        }
 
        public string Name
        {
            set
            {
                displayName = value;
                OnPropertyChanged("Name");
            }
            get
            {
                return displayName;
            }
        }
 
        public event PropertyChangedEventHandler 
            PropertyChanged;
 
        private void OnPropertyChanged(String info)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new 
                                PropertyChangedEventArgs(info));
        }
    }
 
    public class SColorList : 
        ObservableCollection<SColor>
    {
 
    }

Under an initialization method, you should then do the following:

        SColorList colorList = 
            (SColorList)FindResource("CheckedSource"); 

After that is done, the binding is complete and you can then add data item into the colorList and it will show up in the list box control.  And the best thing is your designer can do “magic” on the DataTemplate.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: