我正在尝试将TextBox控件双向绑定到INotifyPropertyChanged对象(Person)中的字符串属性。在加载表单时调用Getter,但该值不会输入到TextBox中。同样,TextBox中的任何更改都不会调用Person对象上的Setter。
XAML
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<TextBox x:Name="txtPersonName"
DataContext="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
</Window>
视图模型
public class Person : INotifyPropertyChanged
{
private string _name= "default value";
public string Name
{
get { return _name; }
set
{
if (value != _name)
{
_name = value;
OnPropertyChanged("Name");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
代码隐藏
public partial class MainWindow : Window
{
private Person viewModel = new Person();
public MainWindow()
{
InitializeComponent();
DataContext = viewModel;
}
}
为什么文本框中输入的文本不会传播回Person对象?
答案 0 :(得分:3)
在XAML
中,您需要设置TextBox的Text
属性而不是DataContext
属性