4

I have a custom MyControl : UserControl with dependency property

string Text 

Inside the MyControl in XAML I have a TextBox.

I wish to bind the Text dependency property of MyControl to the Text dependency property of the TextBox.

What is the best way to do this? Can I declare the dependency property of MyControl to pass through to the child depenendency property?

0

2 Answers 2

5

The easiest way is to assign a x:Name="root" attribute to the root of your MyControl.xaml file, and then use a binding like this for your TextBox:

<TextBox Text="{Binding Text, ElementName=root}" /> 

(You can specify your own name for root.)

Sign up to request clarification or add additional context in comments.

6 Comments

But does that implicitly create the DP on the user control. I would still have to declare it in code behind right?
You absolutely have to declare your property on the user control; there's no implicit creation of a property just because you bind to it. Your question states that you have a custom control with that dependency property already and is asking for help binding to it; if that's not the case then you should possibly reword your question.
Nah I was just curious. There are lots of dark corners in WPF. It wouldn't have surprised me if it were possible :)
This works, but what about when you want to specify a StringFormat in the binding such as: UnitlessValue="{Binding NumberAsPercent, StringFormat=P1}, has anyone found a way to do this?
@GetFuzzy: have you tried {Binding NumberAsPercent, ElementName=root, StringFormat=P1}?
|
1

My answer here details a nice example of how you can accomplish this. You'll essentially have your controls bound to properties on your view models, with the child view model having a dependency property that enables binding on the child control and can push the value to the child's view model. The example is in Silverlight but the implementation is the same for WPF.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.