2013-07-29 26 views
1

我有一个MainWindow,并在其中包含UserControl1和UserControl2,它们都包含一个TextBox。如何在不同的用户控件中绑定文本框

什么是绑定这两个文本框的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> 

提前任何帮助谢谢,

维杰

+0

我改变UserControl2.xaml此,而是它没有工作:“<用户控件X:类= “DataBindTest1.UserControl2” 的xmlns =“HTTP://schemas.mic rosoft.com/winfx/2006/xaml/presentation” 的xmlns:X = “http://schemas.microsoft.com/winfx/2006/xaml” 的xmlns:控制= “CLR-名称空间:DataBindTest1”> ' – vijay

回答

1

你可能在两个文本框的Text属性绑定到相同的视图模型对象,它被设置为MainWindowDataContext和继承到用户控件的属性:

<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属性的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"); 
     } 
    } 
} 
+0

Hi Clemens。这对我想要做的事情有效。并有助于发展我对WPF数据绑定的理解。谢谢。 (对不起,我不能提供你的答案,因为我今天只加入堆栈溢出并且没有最低的声望级别来这么做)。 – vijay

+0

不客气。您可以通过检查左侧的接受标记来接受答案。请参阅[这里](http://meta.stackexchange.com/a/5235)它是如何工作的。 – Clemens

+0

哦,是的,那是你怎么做的。谢谢。 – vijay

相关问题