Sauce
Sauce

Reputation: 93

PropertyChanged event not Handled properly

I'm trying to get my property changed event handler working, and I've checked with the dubugger the OnPropertyChanged method is being called, but it's not invoking the method like I was expecting it to.

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");
    }
}

I've stepped through this with the debugger, the constructor for MainViewModel() gets called, and adds the PropertyChangedEventHandler. At this point, _characterSelection's PropertyChanged event has this value: (From the locals tab in the debugger)

{Method = {Void characterSelection_PropertyChanged(System.Object, System.ComponentModel.PropertyChangedEventArgs)}}

Once newCharacter method in the CharacterSelectionViewModel gets called, it calls OnPropertyChanged. At this point, _characterSelection's PropertyChanged event has this value:

{Method = {Void OnPropertyChanged(System.Object, System.ComponentModel.PropertyChangedEventArgs)}}

The OnPropertyChanged event gets to the handler(this, new PropertyChangedEventArgs(property)); line, but characterSelection_PropertyChanged() is never invoked. No errors are thrown.

What did I miss? Thanks for any help.

Upvotes: 1

Views: 881

Answers (1)

Gjeltema
Gjeltema

Reputation: 4156

You may have the binding set up such that you are having a separate instance of CharacterSelectionViewModel instead of the instance on MainViewModel. Check your bindings to ensure that you're properly bound to the MainViewModel, and that you're utilizing its instance of CharacterSelectionViewModel for your ICommand binding to ensure that the event that you're subscribing to (on the correct instance) is properly raised.

Upvotes: 2

Related Questions