Setting up binding to a custom DependencyProperty inside a WPF user control

亡梦爱人 提交于 2019-12-03 13:07:31

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>

You could also define the binding in the constructor of MainWindow, like this:

public MainWindow()
{
    InitializeComponent();
    SetBinding(MyDPProperty, "MyVMProperty");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!