TextPreview for Textbox

重写问题以澄清我的需求:

我想在文本Textboxes空白时添加预览文本,就像你们中的一些人可能从Xamarin那里知道的那样。

我在SO上找到了这个答案。

这是我上面链接的答案中的Style

          

我得到以下结果:

在此处输入图像描述

由于这很好用,我想将它应用于该Window每个TextBox 。 所以我的方法是改变这一行:

我想可能会做的伎俩,但它不起作用。

我想这是Tag属性和它的Type (object instead of string)

由于第一种方法像魅力一样工作,我真的不明白为什么我需要一个自定义控件…

所以我尝试的是这样的:

        

我错过了什么 – 为什么不工作?

对于可重用文本框,您需要创建自定义控件。 另外,对于绑定也不适用于可视刷,因此您需要一些临时对象来存储该值。 请参考下面的代码。

            public class Temp : Freezable { // Dependency Property public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(string), typeof(Temp), new FrameworkPropertyMetadata(string.Empty)); // .NET Property wrapper public string Value { get { return (string)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } } protected override System.Windows.Freezable CreateInstanceCore() { return new Temp(); } } public class WatermarkTextBox : TextBox { static WatermarkTextBox() { DefaultStyleKeyProperty.OverrideMetadata(typeof(WatermarkTextBox), new FrameworkPropertyMetadata(typeof(WatermarkTextBox))); } public static readonly DependencyProperty WatermarkProperty = DependencyProperty.Register("Watermark", typeof(string), typeof(WatermarkTextBox)); public string Watermark { get { return (string)GetValue(WatermarkProperty); } set { SetValue(WatermarkProperty, value); } } }