WPF将usercontrol的属性绑定到父级的属性 [英] WPF bind usercontrol's property to parent's property

查看:597
本文介绍了WPF将usercontrol的属性绑定到父级的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个usercontrol,它具有2个依赖项属性。我想将这些依赖项属性绑定到mainViewModel的属性,以便每当用户控件中的某些内容发生更改时,父级的属性就会更新。

I have created a usercontrol, which has 2 dependency properties. I want to bind those dependency properties to the mainViewModel's property, so that whenever something gets changed in the user-control the parent's property gets updated.

我尝试将其正常绑定但这没用。我该如何将用户控件的DP绑定到父级的属性。

I tried, binding it normally but it didn't work. How can I bind the user-control's DP to the parent's property.

我尝试了以下操作:
UC:

I tried this: UC:

<TextBox Name="TextBox" Text="{Binding ElementName=UCName, Path=DP1, Mode=TwoWay}"/>

MainWindow:

MainWindow:

<UCName:UCName Width="330" CredentialName="{Binding Path=DP1, Mode=TwoWay}"></UCName:UCName>

谢谢

推荐答案

要绑定到父级的属性,应在Binding中使用RelativeSource。像这样:

For binding to the parent's properties you should use RelativeSource in your Binding. Like this:

<TextBox Name="TextBox" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UCName:UCName}}, Path=DP1, Mode=TwoWay}"/>

详细信息: https://msdn.microsoft.com/zh-CN/library/ms743599(v = vs.100).aspx

ps:不要忘记定义命名空间UCName。

ps: Don't forget define namespace UCName.

已将URL更改为.NET 4版本文档。

Changed URL to .NET 4 version of documentation.

这篇关于WPF将usercontrol的属性绑定到父级的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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