WPF bind usercontrol's property to parent's property

可紊 提交于 2019-12-10 01:59:55

问题


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.

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

I tried this: 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


回答1:


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}"/>

Details: https://msdn.microsoft.com/en-us/library/ms743599(v=vs.100).aspx

ps: Don't forget define namespace UCName.

[EDIT] Changed URL to .NET 4 version of documentation.




回答2:


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.



来源:https://stackoverflow.com/questions/11550247/wpf-bind-usercontrols-property-to-parents-property

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