我有一个课程如下
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中,我有[编辑]
<MenuItem Name="ToolTips"
Header="Tool Tips"
IsCheckable="True"
IsChecked="{Binding Source=CurrentConfig,
Path=IsToolTips,
Mode=TwoWay}"
Click="onToolTipsClick">
</MenuItem>
[结束编辑] 问题是我的Configuration类的“PropertyChanged”成员始终设置为null。我哪里错了?
答案 0 :(得分:3)
问题是你的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;
此外,您的绑定设置为Source=CurrentConfiguration
,但您的媒体资源名称似乎为CurrentConfig
。您可能需要调整数据上下文或绑定路径。将DataContext设置为显示后,您可以删除源,因为您希望绑定绑定到自身。
答案 1 :(得分:2)
Source=CurrentConfiguration
将Source
设置为字符串"CurrentConfiguration"
,显然不具备该属性。
Debug your binding和see the references如果你对它们不够了解的话。
答案 2 :(得分:0)
删除空检查。当您通常实现INotifyProperty时,不要检查它。
public string _PhoneNumber
public string PhoneNumber
{
get
{
return _PhoneNumber;
}
set
{
if (value != PhoneNumber)
{
_PhoneNumber = value;
NotifyPropertyChanged("PhoneNumber");
}
}
}