SL复习笔记之平稳转型——基础篇(五、数据绑定)

关于对象绑定,简单的先提一下,后面再详细的讲解。

一、将对象的属性绑定到SL控件的属性之上,对象可以放在Collection集合中。

      可以将“对象”绑定到UI元素的“DataContext”属性,例如是,TextBox,然后在Textbox的“Text”属性中再设置“{Binding NotePad,Mode=TwoWay}”

二、绑定数据的三种模式:OneTime(只改变一次)、OneWay(单向改变)、TwoWay(双向改变)。

      不多做解释了,看代码。

      public class NotepadItem:INotifyPropertyChanged
    {
        public string _title;
        public string Title
        {
            get { return _title; }
            set
            {
                _title = value;
                NotifyPropertyChanged("Title");
            }
        }

        public string _intro;
        public string Intro
        {
            get { return _intro; }
            set
            {
                _intro = value;
                NotifyPropertyChanged("Intro");
            }
        }

        public string _cont;
        public string Cont
        {
            get { return _cont; }
            set
            {
                _cont = value;
                NotifyPropertyChanged("Cont");
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string propertyName)
        {
            if (null != PropertyChanged)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

      

前台XAML:

<ListBox x:Name="FirstListBox" Margin="0,0,-12,0" ItemsSource="{Binding Items}" SelectionChanged="FirstListBox_SelectionChanged" >
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                          <StackPanel Margin="0,0,0,17" Width="432">
                                <TextBlock Text="{Binding Title}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                                <TextBlock Text="{Binding Intro}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
                          </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>

这里对象“NotepadItem”实现了“INotifyPropertyChanged”接口,当其属性改变时,触发“PropertyChanged”事件。这里牵扯到“委托”、“事件”、“接口”。理解起来有点抽象,在下面再详细的作总结。

最新资料大全传送阵

原文地址:https://www.cnblogs.com/ssol/p/2138410.html