如何在不同的用户控件中绑定文本框

时间:2013-07-29 07:22:17

标签: wpf data-binding user-controls

我有一个MainWindow,其中包含一个TextBox的UserControl1和UserControl2。

绑定这两个文本框的Text属性的最佳方法是什么。

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>

提前感谢您的帮助,

维杰

1 个答案:

答案 0 :(得分:1)

您可以将两个TextBox中的Text属性绑定到同一ViewModel对象的属性,该对象设置为DataContext MainWindow并继承到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>

具有{User}控件绑定到的Text属性的ViewModel类:

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");
        }
    }
}