我试图让 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 对象?