将 ViewModel 绑定到 CustomControl

Bind ViewModel to CustomControl

My Main window 有侧边栏菜单。单击菜单上的项目时,我将在 ContentControl 上呈现该项目的页面 (UserControl)。这是它的样子。

我的 MainViewModel

public MainViewModel()
{
    SystemMenu = new List<SystemMenuViewModel>();
    SystemMenu.Add(new SystemMenuViewModel("Dashboard", new Dashboard()));
    SystemMenu.Add(new SystemMenuViewModel("Appointments", new Dashboard()));
    SystemMenu.Add(new SystemMenuViewModel("Reports", new Reports()));
    SystemMenu.Add(new SystemMenuViewModel("Configuration", new Configuration()));
}

private string _windowTitle = GlobalVariables.WindowTitleDefault;
private string _currentPage = "Dashboard";

public string WindowTitle
{
    get { return _windowTitle; }
    set
    {
    _windowTitle = value;
    NotifyOfPropertyChange(() => WindowTitle);
    }
}

public string CurrentPage
{
    get { return _currentPage; }
    set
    {
    _currentPage = value;
    NotifyOfPropertyChange(() => CurrentPage);
    }
}

public List<SystemMenuViewModel> SystemMenu { get; set; }

我的 SystemMenuViewModel

private string _name;
private object _content;

public SystemMenuViewModel(string name, object content)
{
    _name = name;
    Content = content;
}

public string Name
{
    get { return _name; }
    set { this.MutateVerbose(ref _name, value, RaisePropertyChanged()); }
}

public object Content
{
    get { return _content; }
    set { this.MutateVerbose(ref _content, value, RaisePropertyChanged()); }
}

public event PropertyChangedEventHandler PropertyChanged;

private Action<PropertyChangedEventArgs> RaisePropertyChanged()
{
    return args => PropertyChanged?.Invoke(this, args);
}

渲染部分我的MainView

<ContentControl Content="{Binding ElementName=lstSystemMenu, Path=SelectedItem.Content}" />

我的主要问题是我只是在我的 MainView 上呈现内容,而没有实际调用或绑定它的 ViewModel。

我确定我的 MVVM 框架实现有问题。请告诉我哪里出了问题以及实现这一点的最佳方法是什么。

看看这个:https://msdn.microsoft.com/en-us/magazine/dd419663.aspx 找不到源 zip,但文章中有大量代码示例。

您需要将 ContentControl 的 Content 属性 绑定到 ViewModel/Model 对象,然后 使用 DataTemplates 创建正确的页面取决于数据上下文。数据模板只需要存储在 ResourceDictionary 中,可以是 ContentControl 或某些上层控件(甚至是应用程序)。 DataTemplates 必须设置 DataType 才能工作。

此外,正如对您的问题的评论中所建议的,视图模型不应具有 "content" 属性 类型的对象。看起来你的 "content" 属性 是一个视图对象或其他东西。如果您不向我们展示更多代码,就无法知道。 ViewModel 不应引用任何视图对象。但是 View 可以在代码隐藏或 XAML.

中引用 ViewModel 类

有两种方法可以绑定到 "current selection"。 使用视图列表中的 "current selected" 信息(例如 SelectedItem),或在 MainViewModel 中添加 属性(例如:SelectedViewModel,然后将 ContentControl 绑定到此 属性.