WPF绑定 mode Using System.ComponentModel; IPropertyChanged, if(this.PropertyChanged!=null){ this.PropertyChanged.Invoke(this,new PropertyChangedEventArgs("Name"))
Mode,它的类型为BindingMode的枚举类型,可以取TwoWay、OneWay、OnTime、OneWayToSource、Default。
oneWay:使用 OneWay 绑定时,每当源发生变化,数据就会从源流向目标。
OneTime: 绑定也会将数据从源发送到目标;但是,仅当启动了应用程序或 DataContext 发生更改时才会如此操作,因此,它不会侦听源中的更改通知。
OneWayToSource: 绑定会将数据从目标发送到源。
TwoWay: 绑定会将源数据发送到目标,但如果目标属性的值发生变化,则会将它们发回给源。
Default: binding的模式根据实际情况来定,如果是可编辑的就是TwoWay,只读的就是OneWay.
<StackPanel>
<TextBox x:Name="tb1" Text="{Binding Path=Value,ElementName=slider1,Mode=TwoWay}"/>
<Slider x:Name="slider1" Maximum="10000000" Minimum="0" Margin="5" Value="{Binding Path=Text,ElementName=tb1,Mode=TwoWay}"/>
</StackPanel>
<StackPanel x:Name="stackPanel">
<TextBox x:Name="txtName" Text="{Binding Path=Name}"/>
<TextBox x:Name="txtName2" Text="{Binding Path=Id}"/>
<Button Click="Button_Click" Height="50" Content="Click here"/>
</StackPanel>
using System.ComponentModel;
Company mCompany;
public MainWindow()
{
InitializeComponent();
mCompany = new Company { Name = "Microsoft",Id=1 };
this.stackPanel.DataContext = mCompany;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Name:"+this.mCompany.Name+","+"Id:"+this.mCompany.Id);
mCompany.Name = "Google";
mCompany.Id = 111;
}
public class Company:INotifyPropertyChanged
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
if(this.PropertyChanged!=null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
}
}
}
private int id;
public int Id
{
get
{
return id;
}
set
{
id = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Id"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}