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
是白色的。
我尝试之前....代码没有funtioning代码。 =( – 0070
)您是否将前景改为黑色? – funseiki
@ 0070对不起,忘了依赖属性的东西,我更新了解决方案的答案,这对我有用 – funseiki