[英]How to set watermark text on watermark textbox
I have a template like this, 我有这样的模板,
<Style x:Key="WaterMarkTextBoxStyle" BasedOn="{StaticResource {x:Type TextBox}}" TargetType="{x:Type TextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Grid>
<ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
<TextBlock x:Name="textBlock" Opacity="0.345" Text="Enter Text Here" TextWrapping="Wrap" Visibility="Hidden" />
</Grid>
<ControlTemplate.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsFocused" Value="False" />
<Condition Property="Text" Value="" />
</MultiTrigger.Conditions>
<Setter Property="Visibility" TargetName="textBlock" Value="Visible" />
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
This seems to work quite nicely as a watermark textbox in WPF, but how can I change what the watermark text will be? 作为WPF中的水印文本框,这似乎很好用,但是如何更改水印文本呢?
Above it is hard coded to Text = 'Enter text here'. 上方是硬编码为Text ='在此处输入文字'。
If I use the above like this, 如果我这样使用以上内容,
<TextBox Style="{StaticResource WaterMarkTextBoxStyle}"></TextBox>
I cannot actually set what the watermark text is. 我实际上无法设置水印文本是什么。
Ideas? 想法?
Use an attached dependency property: 使用附加的依赖项属性:
public static class Watermark
{
public static readonly DependencyProperty TextProperty =
DependencyProperty.RegisterAttached( "Text",
typeof(Boolean),
typeof(Watermark),
new FrameworkPropertyMetadata() );
public static void SetText( UIElement element, Boolean value )
{
element.SetValue( TextProperty, value );
}
public static Boolean GetText( UIElement element )
{
return (Boolean)element.GetValue( TextProperty );
}
}
Then for your control you'd do something like: 然后,为了控制您,您可以执行以下操作:
<TextBox Style="{StaticResource WaterMarkTextBoxStyle}" Watermark.Text="Search" />
Your style would then need to bind to the DP: 然后,您的样式需要绑定到DP:
<TextBlock x:Name="textBlock" Opacity="0.345"
Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=(local:Watermark.Text)}"
TextWrapping="Wrap" Visibility="Hidden" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.