2012-11-08 95 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