我正在尝试创建用于在WPF文本框中显示提示文本的参数化样式。原始代码取自this SO question(我向HintText属性添加了绑定)。它确实没有绑定功能。但是当我将HintText
绑定到Content
的Label
时没有运气:
<Window.Resources>
<Style x:Key="HintTextStyle" TargetType="{x:Type TextBox}">
<Style.Resources>
<VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Center" Stretch="None">
<VisualBrush.Visual>
<Label Content="{Binding Path=(local:HintTextProperties.HintText), RelativeSource={RelativeSource AncestorType={x:Type TextBox}}}"
Foreground="LightGray" />
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<Style.Triggers>
<Trigger Property="Text" Value="{x:Static sys:String.Empty}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<TextBox Height="23" Margin="100,100" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="120"
local:HintTextProperties.HintText="Some hint text"
Style="{DynamicResource HintTextStyle}" />
<Button Content="Button" HorizontalAlignment="Left" Margin="361,166,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
依赖项属性:
public class HintTextProperties
{
public static string GetHintText(DependencyObject obj)
{
return (string)obj.GetValue(HintTextProperty);
}
public static void SetHintText(DependencyObject obj, string value)
{
obj.SetValue(HintTextProperty, value);
}
public static readonly DependencyProperty HintTextProperty =
DependencyProperty.RegisterAttached(
"HintText",
typeof(string),
typeof(HintTextProperties),
new FrameworkPropertyMetadata(""));
}
此代码有什么问题?
您可以使用此:
<Style x:Key="placeHolder" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Grid>
<TextBox Text="{Binding Path=Text,
RelativeSource={RelativeSource TemplatedParent},
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"
x:Name="textSource"
Background="Transparent"
Panel.ZIndex="2" />
<TextBox Text="{TemplateBinding Tag}" Background="{TemplateBinding Background}" Panel.ZIndex="1">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Foreground" Value="Transparent"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Text, Source={x:Reference textSource}}" Value="">
<Setter Property="Foreground" Value="LightGray"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
用法:
<TextBox Style="{StaticResource placeHolder}" Tag="Name of customer" Width="150" Height="24"/>