我正在尝试让我的属性更改事件处理程序正常工作,并且我已经使用调试器检查了正在调用 OnPropertyChanged 方法,但它并没有像我期望的那样调用该方法。
public class MainViewModel : ObservableObject
{
public MainViewModel()
{
_characterSelection = new CharacterSelectionViewModel();
_characterSelection.PropertyChanged += new PropertyChangedEventHandler(characterSelection_PropertyChanged);
}
private void characterSelection_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName.Equals("Character"))
{
_character = _characterSelection.Character;
_currentView = _newCharacter;
OnPropertyChanged("CurrentView");
}
}
}
[Serializable]
public class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string property)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(property));
}
}
}
public class CharacterSelectionViewModel : ObservableObject
{
private void newCharacter()
{
CharacterSaver.SaveCharacter(CharacterName, _character);
OnPropertyChanged("Character");
}
}
我已经使用调试器逐步完成了此操作,MainViewModel()
调用了构造函数,并添加了PropertyChangedEventHandler
. 此时,_characterSelection's PropertyChanged
事件具有以下值:(来自调试器中的本地选项卡)
{Method = {Void characterSelection_PropertyChanged(System.Object, System.ComponentModel.PropertyChangedEventArgs)}}
一旦调用newCharacter
中的方法CharacterSelectionViewModel
,它就会调用OnPropertyChanged
. 此时,_characterSelection's PropertyChanged
事件有这个值:
{Method = {Void OnPropertyChanged(System.Object, System.ComponentModel.PropertyChangedEventArgs)}}
事件OnPropertyChanged
到达handler(this, new PropertyChangedEventArgs(property));
线路,但从characterSelection_PropertyChanged()
未被调用。没有错误被抛出。
我错过了什么?谢谢你的帮助。