Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exposing Child Control Dependency Properties for Binding in WPF

I have a very simple UserControl called CustomTextBox with this XAML:

<UserControl x:Class="CustomTextBox" ... >
    <Grid>
        <TextBox x:Name="InnerTextBox"/>
    </Grid>
</UserControl>

Now when I use CustomTextBox and want to do binding to InnerTextBox.Text, it does not work:

... {Binding ElementName=CustomTextBox, Path=InnerTextBox.Text}

I tried it another way, does not work as well:

... {Binding ElementName=CustomTextBox.InnerTextBox, Path=Text}

I know I can define a new dependency property called CustomTextBox.Text and then bind it to InnerTextBox.Text but I am planning to have custom controls with many properties and it is hell of a work to copy all of them just to support binding. Furthermore, copying/wrapping properties means each value is stored twice.

In WinForms, this was a matter simple inheritance and all the properties were available automatically. In WPF, inheritance of XAML controls is not possible and the properties are inaccessible.

Is there any simple way on how to set up binding from some control to UserControl's child element property?

like image 723
Libor Avatar asked Dec 01 '13 11:12

Libor


1 Answers

1.in the code behind of your control create a new DP ,say we call it Text
2. in the xaml from your code :

<TextBox x:Name="InnerTextBox" Text={Binding Text}/> 


3.make sure that the DataContext of the textBox is the UserControl

like image 170
ZSH Avatar answered Oct 05 '22 04:10

ZSH