簡體   English   中英

如何將用戶控件的文本框中的文本綁定到文本塊中?

[英]How to bind the text in a textbox of a usercontrol into a textblock?

我創建了一個用戶控件文本框,我想將文本塊綁定到我在用戶控件文本框中鍵入的內容。 我嘗試了一些代碼,但是沒有用。 有人可以教我嗎? 謝謝

我的userControl TextBox:

<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>

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

}

[MainWindow] .xaml:

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

本質上,添加依賴項屬性使您可以在用戶控件中公開要在XAML中進行修改的值(以及通常的綁定)。


您可能還需要將TextBlockForeground (文本顏色)屬性更改為比白色更深的顏色,因為默認情況下, Background為白色。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM