将 ViewModel 绑定到 ContentControl 作为其 DataContext [英] Binding ViewModel to ContentControl as its DataContext

查看:54
本文介绍了将 ViewModel 绑定到 ContentControl 作为其 DataContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在按钮点击时更改 UserControls(我不会在这里复杂化,所以我只会提到重要的部分).所以想法是将那些 UserControls 的 ViewModels 绑定到 ContentControl,然后使用 DataTemplates 将它们关联到 Views.代码如下:

I want to change UserControls on button clicks (I'm not going to complicate here, so I'll only mention important parts). So idea was to bind ViewModels of those UserControls to ContentControl, and than associate them Views using DataTemplates. Here's the code:

<Window x:Class="Project.MainWindow">
<Window.Resources>
    <DataTemplate DataType="{x:Type UserControl:ViewUserControlViewModel}" >
        <UserControl:ViewUserControl/>
    </DataTemplate>
    <DataTemplate DataType="{x:Type UserControl:EditUserControlViewModel}" >
        <UserControl:EditUserControl/>
    </DataTemplate>
</Window.Resources>
<Grid>
    <ContentControl DataContext="{Binding UserControlViewModel}" />
    <Button Content="View" Click="ChangeToView()"/>
    <Button Content="Edit" Click="ChangeToEdit()"/>
</Grid>
</Window>

视图模型:

public class MainWindowViewModel : DependencyObject
{
    public DependencyObject UserControlViewModel
    {
        get { return (DependencyObject)GetValue(UserControlViewModelProperty); }
        set { SetValue(UserControlViewModelProperty, value); }
    }
    public static readonly DependencyProperty UserControlViewModelProperty = 
           DependencyProperty.Register("UserControlViewModel", typeof(DependencyObject), typeof(MainWindowViewModel), new PropertyMetadata());

    public MainWindowViewModel()
    {
        UserControlViewModel = new EditUserControlViewModel();
    }
}

但是有一个问题.当我开始项目时,我只看到按钮而不是任何用户控件.我做错了什么?

But theres a problem. When I start project, I only see buttons but not any UserControls. What did I do wrong?

推荐答案

如果您的 Window.DataContext 正确设置为 MainWindowViewModel 这应该可以完成工作

If your Window.DataContext is properly set to MainWindowViewModel this should do the job

<ContentControl Content="{Binding UserControlViewModel}" />

这篇关于将 ViewModel 绑定到 ContentControl 作为其 DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆