绑定到样式

时间:2016-01-30 20:58:22

标签: wpf xaml

在开始之前,我的最终目标是为所有控件设置默认的工具提示样式,当正在显示工具提示的控件出现验证错误时,该边框会变为红色。

因此,ToolTip具有PlacementTarget属性,该属性是显示工具提示的控件。有一个Validation.HasError附加属性,当它具有数据绑定错误时,该属性在该PlacementTarget控件上设置。例如,我有一个TextBox,在TextBox样式中,我可以这样做:

<Style TargetType="{x:Type TextBox}">
    <Style.Triggers>
        <Trigger Property="Validation.HasError" Value="True">
            <Setter Property="ToolTip">
                <Setter.Value>
                    <ToolTip Content="{Binding RelativeSource={RelativeSource Self}, Path=PlacementTarget.(Validation.Errors)[0].ErrorContent}"/>

现在,我可以为工具提示创建一个带有红色边框的样式,并将其设置在上面的触发器中,但我不想在每个控件的样式触发器中都这样做,所以我希望我的工具提示样式尽可能自己处理这个功能。

我尝试了各种各样的东西,最近一次(如果出现错误,转换器基本上会返回红色,否则会变黑):

<Style TargetType="{x:Type ToolTip}">
    <Setter Property="BorderBrush" Value="{Binding Path=PlacementTarget.Validation.HasError, RelativeSource={RelativeSource Self}, Converter={StaticResource ToolTipBorderConverter}}"/>
</Style>

但是从错误中可以看出,它试图在TextBox上获得一个名为Validation的实际属性,而不是附加属性:

System.Windows.Data Error: 40 : BindingExpression path error: 'Validation' property not found on 'object' ''TextBox' (Name='')'. BindingExpression:Path=PlacementTarget.Validation.HasError; DataItem='ToolTip' (Name=''); target element is 'ToolTip' (Name=''); target property is 'BorderBrush' (type 'Brush')

我也尝试过这样的事情:

<Style TargetType="{x:Type ToolTip}">
    <Style.Triggers>
        <Trigger Property="PlacementTarget.Validation.HasError" Value="True">
            <Setter Property="BorderBrush" Value="Red"/>

但是我得到一个错误,说我不能像那样嵌套Trigger的属性。

有没有办法完成我在这里尝试做的事情?

1 个答案:

答案 0 :(得分:1)

搜索了几个小时的答案,发布后我看到一篇相关的文章给我答案:你必须在括号中包装Validation.HasError,以便将其识别为附加属性。

<Style TargetType="{x:Type ToolTip}">
    <Setter Property="BorderBrush" Value="{Binding Path=PlacementTarget.(Validation.HasError), RelativeSource={RelativeSource Self}, Converter={StaticResource ToolTipBorderConverter}}"/>