C#C
C#4y ago
AfterLife

WPF MVVM PropertyChangedEventHandler always null - Not updating Binding [Answered]

I have a MainWindow which loads a view (UserControl) in a ContentControl as Content per Binding to an Property in my MainViewModel.
The initial Load works fine but changes made afterwards don't get published to the MainView.

OnPropertyChanged is being called- and INotifyPropertyChanged is implemented via an "ObservableObject" Wrapper-Class.
The PropertyChangedEventHandler is always null the View never attaches to it.

My MainWindow
<Window x:Class="_505_GUI_Battleships.MainWindow"
       [...]>

    <Window.DataContext>
        <viewModel:MainViewModel/>
    </Window.DataContext>

    <Grid Margin="0 2 0 0">
    [...]
        <ContentControl Grid.Row="1" Content="{Binding Path=CurrentView, UpdateSourceTrigger=PropertyChanged}" />
    </Grid>
</Window>


My ViewModel
public class MainViewModel : ObservableObject
{
    private readonly MainModel _mainModel;

    internal readonly DummyViewModel? DummyVm;
    internal readonly StartViewModel? StartVm;

    private object _currentView = null!;

    public object CurrentView
    {
        get => _currentView;
        set => Update(ref _currentView, value);
    }

    public ICommand StartViewModelCommand => new RelayCommand(_ => _mainModel.ChangeView(ViewChanged, StartVm));
    [...]

    public MainViewModel()
    {
        _mainModel = new MainModel();

        StartVm = new StartViewModel();
        DummyVm = new DummyViewModel();

        CurrentView = StartVm;
    }

    private void ViewChanged(object view)
    {
        CurrentView = view;
    }
}


public sealed class MainModel
{
    public void ChangeView(Action<object> action, object? param)
    {
        if ( param != null )
            action(param);
    }
}
Was this page helpful?