【发布时间】:2017-12-24 15:22:03
【问题描述】:
PropertyChanged 始终为 null,并且名称不会显示在窗口上。应该是罗马音。你知道为什么它总是为空而不显示名称吗?
我的窗户课
public partial class MainWindow : Window, INotifyPropertyChanged
{
string _name;
public event PropertyChangedEventHandler PropertyChanged;
public string PersonName
{
get => _name;
set
{
_name = value;
OnPropertyChanged("PersonName");
}
}
public MainWindow()
{
InitializeComponent();
_name = "Adam";
PersonName = "Roman";
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
我的 XAML
<Grid>
<Label x:Name="Test" Width="100" Height="50" Foreground="Black" Content="{Binding PersonName, Mode=TwoWay}"></Label>
</Grid>
【问题讨论】:
-
您在 XAML 中的何处设置 DataContext?如果不将 DataContext 设置在某个地方,您的绑定将无法正常工作。
-
我不知道我必须设置 DataContext,现在它可以工作了,谢谢
-
如果你在后面的代码中,这有什么意义?
-
将 INPC 属性放入 viewmodel 类中。将 viewmodel 类的实例分配给 MainWindow 的 DataContext 属性
标签: c# wpf inotifypropertychanged