我将尝试使用附加属性在TextBox的背景中创建一个提示文本标签,但是我无法解决样式资源中文本标题的绑定:
样式定义:
<Style x:Key="CueBannerTextBoxStyle"
TargetType="TextBox">
<Style.Resources>
<VisualBrush x:Key="CueBannerBrush"
AlignmentX="Left"
AlignmentY="Center"
Stretch="None">
<VisualBrush.Visual>
<Label Content="{Binding Path=(EnhancedControls:CueBannerTextBox.Caption), RelativeSource={RelativeSource AncestorType={x:Type TextBox}}}"
Foreground="LightGray"
Background="White"
Width="200" />
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<Style.Triggers>
<Trigger Property="Text"
Value="{x:Static sys:String.Empty}">
<Setter Property="Background"
Value="{DynamicResource CueBannerBrush}" />
</Trigger>
<Trigger Property="Text"
Value="{x:Null}">
<Setter Property="Background"
Value="{DynamicResource CueBannerBrush}" />
</Trigger>
<Trigger Property="IsKeyboardFocused"
Value="True">
<Setter Property="Background"
Value="White" />
</Trigger>
</Style.Triggers>
</Style>
附加属性:
public class CueBannerTextBox
{
public static String GetCaption(DependencyObject obj)
{
return (String)obj.GetValue(CaptionProperty);
}
public static void SetCaption(DependencyObject obj, String value)
{
obj.SetValue(CaptionProperty, value);
}
public static readonly DependencyProperty CaptionProperty =
DependencyProperty.RegisterAttached("Caption", typeof(String), typeof(CueBannerTextBox), new UIPropertyMetadata(null));
}
使用方法:
<TextBox x:Name="txtProductInterfaceStorageId"
EnhancedControls:CueBannerTextBox.Caption="myCustomCaption"
Width="200"
Margin="5"
Style="{StaticResource CueBannerTextBoxStyle}" />
这个想法是在创建文本框时定义视觉刷选中使用的文本提示,但我遇到了绑定错误:
System.Windows.Data Error: 4 : 找不到引用'RelativeSource FindAncestor,AncestorType='System.Windows.Controls.TextBox',AncestorLevel='1''的绑定源。BindingExpression:Path=(0); DataItem=null; target element is 'Label' (Name=''); target property is 'Content' (type 'Object')
如果我只是在样式中硬编码Label.Content属性,那么代码能正常工作。
有什么想法吗?