绑定到其他控件的视图模型

时间:2017-01-29 09:22:04

标签: wpf data-binding

我试图绑定到包含控件的ViewModel中的属性,但似乎WPF不允许我绑定到该属性。尝试执行此操作时,它会报告错误:Windows Presentation Foundation(WPF)项目不支持 ViewModel。

我有没有办法使用XAML绑定到ViewModel中的属性,还是必须在代码后面执行所有ViewModel修改?

主窗口XAML:

<Window x:Class="MyNamespace.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:MyNamespace"
    mc:Ignorable="d"
    Title="MainWindow">
<Grid>
    <!-- Error: Can't bind to ViewModel.MyValue -->
    <local:UserControl1 ViewModel.MyValue="123"/>
</Grid>

用户控制类:

public partial class UserControl1 :UserControl
{
    public UserControl1()
    {
        InitializeComponent();

        ViewModel = new UserControlViewModel();
    }

    public UserControlViewModel ViewModel
    {
        get
        {
            return (UserControlViewModel) GetValue(ViewModelProperty);
        }
        set
        {
            SetValue(ViewModelProperty, value);
        }
    }

    public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register(nameof(ViewModel), typeof(UserControlViewModel), typeof(UserControl1), new PropertyMetadata(null));
}

用户控制的视图模型类:

public class UserControlViewModel
{
    public string MyValue
    {
        get;
        set;
    }
}

1 个答案:

答案 0 :(得分:1)

不,您不能使用XAML设置控件的依赖项属性的嵌套属性:

Can I use XAML to set a nested property (property of the value of a property) of a control?

您只能设置属性本身的值:

<local:UserControl1>
    <local:UserControl1.ViewModel>
        <local:UserControlViewModel MyValue="123" />
    </local:UserControl1.ViewModel>
</local:UserControl1>