vijay
vijay

Reputation: 13

How to bind textboxes in different user controls

I have a MainWindow, and within it UserControl1 and UserControl2, which both contain a TextBox.

What is the best way to bind the Text property of these 2 textboxes.

MainWindow.xaml

<Window x:Class="DataBindTest1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Controls="clr-namespace:DataBindTest1">
    <StackPanel>
        <Controls:UserControl1/>
        <Controls:UserControl2/>
    </StackPanel>
</Window>

UserControl1.xaml

<UserControl x:Class="DataBindTest1.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <TextBox Name="uc1TextBox">ExampleText</TextBox>
    </Grid>
</UserControl>

UserControl2.xaml

<UserControl x:Class="DataBindTest1.UserControl2"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
            <TextBox Name="uc2TextBox" /> <!--I want this to be bound to the Text property of uc1TextBox (which is in UserControl1)-->
    </Grid>
</UserControl>

Thanks in advance for any help,

Vijay

Upvotes: 1

Views: 836

Answers (1)

Clemens
Clemens

Reputation: 128061

You may bind the Text property in both TextBoxes to a property of the same ViewModel object, which is set to the DataContext of MainWindow and inherited to the UserControls:

<UserControl x:Class="DataBindTest1.UserControl1" ...>
    <Grid>
        <TextBox Text="{Binding SomeText}"/>
    </Grid>
</UserControl>

<UserControl x:Class="DataBindTest1.UserControl2" ...>
    <Grid>
        <TextBox Text="{Binding SomeText}"/>
    </Grid>
</UserControl>

<Window x:Class="DataBindTest1.MainWindow" ...>
    <Window.DataContext>
        <local:ViewModel/>
    </Window.DataContext>
    <StackPanel>
        <Controls:UserControl1/>
        <Controls:UserControl2/>
    </StackPanel>
</Window>

The ViewModel class with the Text property that both UserControls bind to:

public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private string someText;
    public string SomeText
    {
        get { return someText; }
        set
        {
            someText= value;
            OnPropertyChanged("SomeText");
        }
    }
}

Upvotes: 1

Related Questions