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
(テキストの色) プロパティを白より暗い色に変更することもできます。TextBlock
Background