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

<Style TargetType="{x:Type local:WriteMark}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:WriteMark}">
<Border BorderBrush="Black" BorderThickness="1" >
<Grid>
<ScrollViewer x:Name="PART_ContentHost" Focusable="False" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
<TextBlock Foreground="#999" x:Name="mark" Visibility="{TemplateBinding ShowMark}" Text="{TemplateBinding PlaceHolder}" />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

使用:

<local:WriteMark Width="100" ></local:WriteMark>

效果:

 

 

 

 

 源代码点我下载

posted @ 2021-06-01 19:09  奇迹之耀  阅读(218)  评论(0编辑  收藏  举报