1

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

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

主窗口.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>

用户控件2.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>

提前感谢您的帮助,

维杰

4

1 回答 1

1

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

Text具有两个 UserControl 绑定到的属性的 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");
        }
    }
}
于 2013-07-29T07:56:41.727 回答