WPF TextBox双向绑定
想实现当前台文本框的值改变时,后台的值也同时改变,然后我设置的Mode=TwoWay,但是不起作用
最后发现需要设置UpdateSourceTrigger=PropertyChanged
更新:不设置UpdateSourceTrigger=PropertyChanged也可以,但是只有当文本框失去焦点时才会改变后台的值
效果:
前台代码:
<Grid>
<TextBox Width="100" Height="30" x:Name="test0" Text="{Binding Test,UpdateSourceTrigger=PropertyChanged}"> </TextBox>
<Label Width="100" Height="30" Margin="0,50,0,0" Content="{Binding Test}"></Label>
</Grid>
后台代码:
public partial class MainWindow : Window, INotifyPropertyChanged
{
private string test = "测试";
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public string Test { get { return test; } set
{
test = value;
OnPropertyChanged("test"); } }
public MainWindow()
{
DataContext = this;
InitializeComponent();
}
}