fahadash
fahadash

Reputation: 3281

WPF Binding: How do I reference element outside a user control?

My main window has following portion of XAML

<StackPanel>
 <TextBox x:Name="textbox1" />
 <my:UserControl1 />
</StackPanel>

my:UserControl1 goes like this

<TextBox x:Name="userControlTextBox" />

I would like to bind the above textbox's Text property to Text property of the textbox outside. I have tried

<TextBox x:Name="userControlTextBox" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Path=textbox1.Text}" />

Upvotes: 1

Views: 2046

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81233

You can't bind like you shown in the question. There are two ways to achieve that:

First, bind Text of textBox1 to some property in ViewModel. And bind Text of userControlTextBox to same bound property.

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

and in UserControl

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

Make sure your property is notifiable (INPC should be implemented by containing class) so that any changes in it gets propagated to GUI.


Second would be to create custom DP on your userControl of type string. Bind that DP with Text value of textbox1. And bind Text of userControlTextBox to that DP.

<StackPanel>
  <TextBox x:Name="textbox1" />
  <my:UserControl1 TextValue="{Binding Text, ElementName=textBox1}"/>
</StackPanel>

Here, TextValue is custom DP declared in your userControl.

public string CustomValue
{
    get { return (string)GetValue(CustomValueProperty); }
    set { SetValue(CustomValueProperty, value); }
}

public static readonly DependencyProperty CustomValueProperty =
    DependencyProperty.Register("CustomValue", typeof(string),
                                 typeof(UserControl1));

Now, bind textBox in UserControl like this:

<TextBox x:Name="userControlTextBox"
         Text="{Binding TextValue, RelativeSource={RelativeSource FindAncestor,
                                         AncestorType=UserControl}}"/>

Upvotes: 1

Related Questions