我有一个类如下
public partial class Configuration : INotifyPropertyChanged
{
private bool _isToolTips;
public bool IsToolTips
{
get { return _isToolTips; }
set { Set(this, "IsToolTips", ref _isToolTips, value, PropertyChanged); }
}
#region INotifyPropertyChanged functionality
public static void Set<T>(object owner, string propName, ref T oldValue, T newValue,
PropertyChangedEventHandler eventHandler)
{
// make sure the property name really exists
if (owner.GetType().GetProperty(propName) == null)
{
throw new ArgumentException("No property named ‘" +
propName + "‘ on " + owner.GetType().FullName);
}
// we only raise an event if the value has changed
if (Equals(oldValue, newValue)) return;
oldValue = newValue;
if (eventHandler != null)
{
eventHandler(owner, new PropertyChangedEventArgs(propName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void notifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
#endregion INotifyPropertyChanged functionality
}
此类在单独的程序集中编译。然后我将它添加到我的 MainWindow 构造函数中,如下所示 [edit]
public MainWindow()
{
initializeAttributes();
InitializeComponent();
CurrentConfig = new Configuration
{
IsToolTips = true
};
DataContext = CurrentConfig;
composeModules();
}
[结束编辑] 在我的 XMAL 中我有这个 [edit]
<MenuItem Name="ToolTips"
Header="Tool Tips"
IsCheckable="True"
IsChecked="{Binding Source=CurrentConfig,
Path=IsToolTips,
Mode=TwoWay}"
Click="onToolTipsClick">
</MenuItem>
[结束编辑] 问题是我的配置类的“PropertyChanged”成员总是设置为空。我哪里错了?
最佳答案
问题是你初始化你的 CurrentConfig
太迟了:
// Setting data context here...
DataContext = CurrentConfig;
InitializeComponent();
// This makes a new instance, but does not update the data context!
CurrentConfig = new Configuration
{
IsToolTips = true
};
我怀疑你想改变这个:
InitializeComponent();
CurrentConfig = new Configuration
{
IsToolTips = true
};
// Set this AFTER you construct your CurrentConfig
DataContext = CurrentConfig;
此外,您的绑定(bind)是使用 Source=CurrentConfiguration
设置的,但您的属性名称似乎是 CurrentConfig
。您可能需要调整数据上下文或绑定(bind)路径。将 DataContext 设置为显示后,您可能会删除源,因为您希望绑定(bind)绑定(bind)到自身。
关于c# - INotifyPropertyChanged 的 PropertyChanged 成员始终为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8976450/