更改ViewModel时窗口不会更新

时间:2011-04-20 17:55:57

标签: wpf mvvm binding view viewmodel

我有一个使用MVVM的WPF应用程序;当我在主窗口ViewModel类中更改ViewModel时,窗口中不会显示新的用户控件...原始的用户控件仍然存在。 ViewModel看起来像这样:

public class MainWindowViewModel : ViewModelBase {

    public ViewModelBase Workspace;

    public MainWindowViewModel()
    {
        var w = new CustomerDetailsViewModel();

        SetActiveWorkspace(w);
    }

    void NavigationService_ViewChanged(object sender, ViewChangedEventArgs e)
    {
        SetActiveWorkspace(e.View);
    }

    void SetActiveWorkspace(ViewModelBase workspace)
    {
        Workspace = workspace;
    }
}

public ViewModelBase Workspace; public MainWindowViewModel() { var w = new CustomerDetailsViewModel(); SetActiveWorkspace(w); } void NavigationService_ViewChanged(object sender, ViewChangedEventArgs e) { SetActiveWorkspace(e.View); } void SetActiveWorkspace(ViewModelBase workspace) { Workspace = workspace; } }

我的XAML看起来像这样:

导航服务ViewChanged事件正在触发,并且正在使用参数中的正确视图调用SetActiveWorkspace方法。但是,之后,视图不会重新加载。我在这里缺少什么?

1 个答案:

答案 0 :(得分:2)

您的Workspace属性未引发PropertyChanged事件。它应该是这样的:

private ViewModelBase _workspace;

public ViewModelBase Workspace
{
    get { return _workspace; }
    set 
    {
        if (value != _workspace)
        {
            _workspace = value;

            // This raises the PropertyChanged event to let the UI know to update
            OnPropertyChanged("WorkSpace");
        }
    }
}

确保您的ViewModelBase实现INotifyPropertyChanged