dbones
dbones

Reputation: 4504

Binding a textbox inside a user control?

I have the following

MyAwesomeControl (user control)

It has a text box inside it. which is bound to a dependency property called Text.

SimpleViewModel

like object (not really a VM, but it gets the point across), sets up a collection of people (which is observable)

it also has a SelectedPerson property, which notifies on change

Main page control

Has its data context set to the SimpleViewModel contains a grid which is bound to the collection of people (this is used to select a person)

MyAwesomeControl with its Text property bound to SelectedPerson.Name

A TextBlock also bound to the SelectedPerson.Name

I made a small solution here : https://skydrive.live.com/redir?resid=82ECBE29B8DC2CD5!300

The issue

when i select a person in the grid the text box in MyAwesomeControl does not update.

the text block on the main form does.

how can we allow the user to supply the binding to the Text of the MyAwesomeControl, and have that update the internal text box (note this control is to be reused, so i cannot be aware of main page specific values)

many thanks

Upvotes: 0

Views: 117

Answers (1)

nemesv
nemesv

Reputation: 139758

When you need to bind to a custom dependecy property inside a custom usercontrol you need to use element binding, and don't set the DataContext inside your user control.

So you need to follow these steps to make your sample work:

  • You need to remove the DataContext = this; from your userControl's constructor

  • Just add a name to your UserControl e.g. <UserControl ... x:Name="Self" >

  • And use ElementName with Self in your text binding (inside MyAwsomeControl.xaml):

    Text="{Binding Text, ElementName=Self, Mode=TwoWay}"
    

If you wan't to make the update work you also need to set Mode to TwoWay where you use your custom control (inside MainPage.xaml):

Text="{Binding SelectedPerson.Name, Mode=TwoWay}"

Upvotes: 1

Related Questions