Silverlight数据绑定oneTime,oneWay,twoWay
oneTime:一次性绑定,将数据给控件,绑定就结束
oneWay:数据源改变会影响绑定该数据源的控件
twoWay:数据源改变会影响绑定该数据源的控件,并且控件中数据改变时也会影响到数据源
一、oneTime
前台:
<TextBox Text="{Binding Name,Mode=OneTime}" Height="23" HorizontalAlignment="Left" Margin="114,92,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
后台:
public class Person { string name; public string Name { get { return name; } set { name = value; } } } Person p = new Person(); public MainPage() { InitializeComponent(); p.Name = "乔峰"; textBox1.DataContext = p; }
二、oneWay
前台:
<TextBox Text="{Binding Name,Mode=OneWay}" Height="23" HorizontalAlignment="Left" Margin="114,92,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" /> <Button Content="oneWay" Height="23" HorizontalAlignment="Left" Margin="159,182,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
后台:
public class Person : INotifyPropertyChanged//要实现oneWay和twoWay的绑定需要实现一个接口 { string name; public string Name { get { return name; } set { name = value; NotifyChange("Name"); } } #region INotifyPropertyChanged 成员 public event PropertyChangedEventHandler PropertyChanged; private void NotifyChange(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #endregion } Person p = new Person(); public MainPage() { InitializeComponent(); p.Name = "乔峰"; textBox1.DataContext = p; } private void button1_Click(object sender, RoutedEventArgs e) { p.Name = "段誉"; }
当点击oneWay这个按钮时,数据源中的改变将会影响绑定了该数据源的控件。
三、twoWay
前台:
<TextBox Text="{Binding Name,Mode=OneWay}" Height="23" HorizontalAlignment="Left" Margin="114,92,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" /> <TextBox Text="{Binding Name,Mode=TwoWay}" Height="23" HorizontalAlignment="Left" Margin="114,144,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" />
后台:
public class Person : INotifyPropertyChanged//要实现oneWay和twoWay的绑定需要实现一个接口 { string name; public string Name { get { return name; } set { name = value; NotifyChange("Name"); } } #region INotifyPropertyChanged 成员 public event PropertyChangedEventHandler PropertyChanged; private void NotifyChange(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #endregion } Person p = new Person(); public MainPage() { InitializeComponent(); p.Name = "乔峰"; textBox1.DataContext = p; textBox2.DataContext = p; }
让textBox1和textBox2都绑定相同的数据源,前者以oneWay模式绑定,后者以twoWay模式绑定。当修改了textBox2文本框中的内容并让文本框失去焦点时,数据源的值也改变,使textBox1和textBox2都显示新的值。
作者:sy
出处:http://www.cnblogs.com/sydeveloper
QQ:522733724
本页版权归作者和博客园所有,欢迎转载,但未经作者同意必须保留此段声明,
且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利