WPF 自定义一个带水印的文本框


初学WPF,仅供参考

创建自定义控件:

public class WriteMark : TextBox
{
static WriteMark()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(WriteMark), new FrameworkPropertyMetadata(typeof(WriteMark)));
}

public string PlaceHolder
{
get { return GetValue(PlaceHolderProperty).ToString(); }
set { SetValue(PlaceHolderProperty, value); }
}

public static readonly DependencyProperty PlaceHolderProperty =
DependencyProperty.Register("PlaceHolder", typeof(string), typeof(WriteMark), new PropertyMetadata("我是默认水印"));
public Visibility ShowMark
{
get { return (Visibility)GetValue(ShowMarkProperty); }
set { SetValue(ShowMarkProperty, value); }
}
public static readonly DependencyProperty ShowMarkProperty =
DependencyProperty.Register("ShowMark", typeof(Visibility), typeof(WriteMark), new PropertyMetadata(Visibility.Visible));

public WriteMark()
{
base.TextChanged += Text_Changed;
}

private void Text_Changed(object sender, RoutedEventArgs e)
{
if (Text != "")
ShowMark = Visibility.Collapsed;
else
ShowMark = Visibility.Visible;

Generic.xaml

使用:

效果:

 源代码:

 https://files.cnblogs.com/files/GongJx/WpfApp2.rar

相关