我可以通过绑定到wpf中父控件的属性的依赖属性在xaml中设置我的用户控件datacontext吗?

时间:2016-11-09 11:52:10

标签: c# wpf xaml

我有一个名为ViewModel的依赖项属性的用户控件。我希望将此属性设置为的值作为此控件的数据上下文。

以下是其用法示例;

<uc:MyCustomControl ViewModel="{Binding CustomControlViewModel}"/>

以下是“MyCustomControl”的ViewModel依赖项属性的代码隐藏

    public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register(
        "ViewModel", typeof(CustomControlViewModel), typeof(MyCustomControl), new PropertyMetadata(default(CustomControlViewModel), PropertyChangedCallback));

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

    private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
    {
        var control = (MyCustomControl) dependencyObject;
        if (control == null)
        {
            return;
        }
        control.DataContext = (CustomControlViewModel) dependencyPropertyChangedEventArgs.NewValue;
    }

这是“MyCustomControl”的构造函数;

    public MyCustomControl()
    {
        InitializeComponent();
    }

这似乎不起作用,我可能做错了什么?

1 个答案:

答案 0 :(得分:2)

DataContext本身就是DependencyProperty。您可以直接将它与您的viewmodel一起分配。

<uc:MyCustomControl DataContext="{Binding CustomControlViewModel}"/>