2012-11-08 47 views
1

我创建一个用户控件文本框,我想将textblock绑定到我在用户控件的文本框中输入的内容。我尝试了一些代码,但它不起作用。任何人都可以教我?由于如何将用户控件文本框中的文本绑定到文本块?

我的用户文本框:

<Grid Background="Silver" Style="{StaticResource EntryFieldStyle}" Width="175" Height="25" Margin="0" >   
    <TextBox Name="watermarkTextBox" Background="Green" />  
</Grid> 

我的XAML代码:

<StackPanel Orientation="Horizontal"> 
     <UserControls:WatermarkTextBox x:Name="usernameArea"/> 
     <TextBlock Text="{Binding ElementName=usernameArea Path=watermarkTextBox.Text}" FontSize="13" Foreground="White"/> 
</StackPanel> 

回答

1

EDIT2:这是使用与实施INotifyPropertyChanged的沿依赖属性做的一种方式。

会发生什么事是我们将在每次更改文本框的文本时触发PropertyChangedEvent。 窗口窗口将通过访问WatermarkTextBox的WatermarkText依赖项属性来订阅此事件。

下面是它的外观:


WatermarkTextbox.xaml:

<TextBox Name="watermarkTextBox" ... 
     TextChanged="watermarkTextBox_TextChanged"/> 

WatermarkTextbox.xaml.cs:

public partial class WatermarkTextBox : UserControl, INotifyPropertyChanged 
{ 
    ... 
    public static readonly DependencyProperty WatermarkTextProperty = 
     DependencyProperty.Register("WatermarkTextProperty", typeof(String), 
     typeof(WatermarkTextBox), new PropertyMetadata(null)); 

    public String WatermarkText 
    { 
     get { return watermarkTextBox.Text; } 
     set { OnPropertyChanged("WatermarkText"); } 
    } 
    public event PropertyChangedEventHandler PropertyChanged; 
    private void OnPropertyChanged(string name) 
    { 
      PropertyChangedEventHandler handler = PropertyChanged; 
      if (handler != null) 
      { 
       handler(this, new PropertyChangedEventArgs(name)); 
      } 
    } 
    private void watermarkTextBox_TextChanged(object sender, TextChangedEventArgs e) 
    { 
      WatermarkText = this.watermarkTextBox.Text; 
    } 

} 

[主窗口]的.xaml:

 <TextBlock Text="{Binding ElementName=usernameArea Path=WatermarkText}" .../> 

添加一个dependency property本质上允许您公开用户控件中的值以修改XAML(以及通常的绑定)。


您也可能希望将TextBlock的属性来更改Foreground(文本颜色)的东西比白人更暗,因为默认情况下,Background是白色的。

+0

我尝试之前....代码没有funtioning代码。 =( – 0070

+0

)您是否将前景改为黑色? – funseiki

+0

@ 0070对不起,忘了依赖属性的东西,我更新了解决方案的答案,这对我有用 – funseiki