10

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

Ali
  • 309
  • 1
  • 5
  • 20

2 Answers2

22

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: RelativeSource Markup Extension

Note: Don't forget define namespace UCName.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
Researcher
  • 419
  • 3
  • 5
6

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.

LadderLogic
  • 1,090
  • 9
  • 17