WPF 将用户控件的属性绑定到父控件的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11550247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF bind usercontrol's property to parent's property
提问by Ali
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.
我创建了一个用户控件,它有 2 个依赖属性。我想将这些依赖属性绑定到 mainViewModel 的属性,这样每当用户控件中的某些内容发生更改时,父级的属性就会更新。
I tried, binding it normally but it didn't work. How can I bind the user-control's DP to the parent's property.
我试过了,正常绑定,但没有用。如何将用户控件的 DP 绑定到父级的属性。
I tried this: UC:
我试过这个:UC:
<TextBox Name="TextBox" Text="{Binding ElementName=UCName, Path=DP1, Mode=TwoWay}"/>
MainWindow:
主窗口:
<UCName:UCName Width="330" CredentialName="{Binding Path=DP1, Mode=TwoWay}"></UCName:UCName>
Thanks
谢谢
回答by Researcher
For binding to the parent's properties you should use RelativeSource in your Binding. Like this:
要绑定到父属性,您应该在绑定中使用 RelativeSource。像这样:
<TextBox Name="TextBox" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UCName:UCName}}, Path=DP1, Mode=TwoWay}"/>
Details: https://msdn.microsoft.com/en-us/library/ms743599(v=vs.100).aspx
详细信息:https: //msdn.microsoft.com/en-us/library/ms743599(v=vs.100).aspx
ps: Don't forget define namespace UCName.
ps:不要忘记定义命名空间UCName。
[EDIT] Changed URL to .NET 4 version of documentation.
[编辑] 将 URL 更改为 .NET 4 版本的文档。
回答by LadderLogic
Something like this:
像这样的东西:
<MainWindow DataContext="mainViewModel">
<local:TestControl ucDependProp="{Binding viewModelProp}/>
</MainWindow>
className: TestControl.xaml
<UserControl Name="thisControl">
<TextBox Text="{Binding ElementName=thisControl, Path=ucDependProp}/>
</UserControl>
The user control shouldn't be aware of the parent view model.
用户控件不应该知道父视图模型。