我正在尝试实现以下 INotifyPropertyChanged 扩展:
Automatically INotifyPropertyChanged (接受的答案) http://ingebrigtsen.info/2008/12/11/inotifypropertychanged-revisited/
但我无法弄清楚为什么我的 PropertyChanged EventHandler 保持为空。 :(
我做了一个非常简单的 WPF 应用程序来测试它,这是我的 XAML 代码:
<StackPanel Orientation="Vertical">
<TextBox Text="{Binding Path=SelTabAccount.Test, UpdateSourceTrigger=PropertyChanged}"></TextBox>
<TextBox Text="{Binding Path=SelTabAccount.TestRelated, UpdateSourceTrigger=PropertyChanged}"></TextBox>
</StackPanel>
还有我的代码:
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private TabAccount _selTabAccount;
public TabAccount SelTabAccount
{
get { return _selTabAccount; }
set
{
_selTabAccount = value;
PropertyChanged.Notify(() => this.SelTabAccount);
}
}
public MainWindow()
{
InitializeComponent();
SelTabAccount = new TabAccount()
{
Test = "qwer",
TestRelated = ""
};
}
}
public partial class TabAccount : INotifyPropertyChanged
{
private string _test;
public string Test
{
get { return _test; }
set
{
_test = value;
PropertyChanged.Notify(() => this.Test);
PropertyChanged.Notify(() => this.TestRelated);
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
public partial class TabAccount
{
private string _testRelated;
public string TestRelated
{
get
{
_testRelated = Test + "_Related";
return _testRelated;
}
set
{
_testRelated = value;
PropertyChanged.Notify(() => this.TestRelated);
}
}
}
在后面的代码中,您将看到一个类(它的部分用于随机测试)具有 2 个属性,它们应该通知属性更改但没有任何反应。
NotificationExtension 是顶部提供的链接的复制和粘贴,位于外部 cs 文件中。
我也尝试过使用“正常”INotifyPropertyChanged 实现来做这个示例,这按预期工作,但我不能用这个扩展类实现它。
希望你能帮我弄清楚。 提前致谢。
最佳答案
只有当您向可视对象提供一些数据源时,绑定(bind)才会起作用。如果您不提供任何数据源并想深入了解属性,则绑定(bind)将不起作用。
在您的 MainWindow 构造函数下,将 Window 的 DataContext 属性设置为数据源。例如:
public MainWindow()
{
InitializeComponent();
// your property setups
this.DataContext = this;
}
本质上,这使得 MainWindow 属性可用于绑定(bind)到 MainWindow 项目的可视化树。
关于c# - INotifyPropertyChanged - 事件保持为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18484581/