设置绑定到 WPF 用户控件内的自定义 DependencyProperty [英] Setting up binding to a custom DependencyProperty inside a WPF user control

查看:31
本文介绍了设置绑定到 WPF 用户控件内的自定义 DependencyProperty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 WPF 用户控件,其中包含一个名为 MyDP 的自定义 DependencyProperty.我想将此绑定到我的 ViewModel 上的一个属性(作为 UserControl 的 DataContext 注入).我知道一种方法是通过在父窗口的 XAML 中的 UserControl 声明中设置绑定,如下所示:

I have a WPF UserControl containing a custom DependencyProperty named MyDP. I want to bind this to a property on my ViewModel (which is injected as the UserControl's DataContext). I know one way to do it by setting the binding in the UserControl's declaration in the parent window's XAML as such:

<Window x:Class="MyNamespace.Views.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:views="clr-namespace:MyNamespace.Views">
    <StackPanel>
        <views:MyControl MyDP="{Binding Path=MyVMProperty, Mode=OneWayToSource}"/>
    </StackPanel>
</Window>

这很好用,但作为替代方案,我是否可以在 UserControl 的 XAML 中设置绑定,类似于如何将 UserControl 中的各个控件的绑定设置为 ViewModel 的其他属性?

This works fine, but as an alternate could I set up the binding inside the UserControl's XAML, similar to how I set the bindings for the individual controls inside the UserControl to other properties of the ViewModel?

推荐答案

你不能直接按照你最初的想法去做.您可能尝试过并遇到了一些编译错误.您不能在 UserControl 的根 XAML 中设置自定义属性内联,因为元素类型是 UserControl,因此编译器会根据该类型而不是您的自定义类型强制执行属性名称.您可以通过更改为附加属性来解决此问题,但这实际上改变了 MyDP 的含义.相反,您可以在样式中为 UserControl 设置默认值,并获得额外的好处,即只需执行原始示例中的操作即可在任何声明的实例上覆盖它.将其设置在 UserControl 的根元素下:

You can't do what you were originally thinking directly. You probably tried and got some compile errors. You can't set a custom property inline in the UserControl's root XAML because the element type is UserControl so the compiler is enforcing property names based on that type, not your custom type. You could get around this by changing to an Attached Property but that actually changes the meaning of MyDP. Instead you can set a default in the Style for the UserControl and get an additional benefit of being able to override it on any declared instance by just doing what's in your original example. Set this under your UserControl's root element:

<UserControl.Style>
    <Style>
        <Setter Property="views:MyControl.MyDp" Value="{Binding Path=MyVMProperty, Mode=OneWayToSource}" />
    </Style>
</UserControl.Style>

这篇关于设置绑定到 WPF 用户控件内的自定义 DependencyProperty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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