1

ユーザー コントロールのテキスト ボックスを作成し、テキスト ブロックをユーザー コントロールのテキスト ボックスに入力した内容にバインドしたいと考えています。いくつかのコードを試してみましたが、うまくいきません。誰でも教えてもらえますか?ありがとう

私のuserControlテキストボックス:

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

1 に答える 1

1

Edit2 : これを行う 1 つの方法は、INotifyPropertyChanged の実装と共に依存関係プロパティを使用することです。

テキストボックスのテキストが変更されるたびに、PropertyChangedEvent が発生します。Window ウィンドウは、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}" .../> 

依存関係プロパティを追加すると、基本的に、XAML での変更のためにユーザー コントロールの値を公開できます (一般的にはバインディングも同様です)。


デフォルトでは は白であるため、のForeground(テキストの色) プロパティを白より暗い色に変更することもできます。TextBlockBackground

于 2012-11-08T05:17:18.853 に答える