应用另一种样式的样式触发器

Kye*_*ica 3 wpf triggers styles

我确信以前已经有人问过这个问题,但我并没有很容易地弄清楚如何表达这个查询。

我有这个风格;

<SolidColorBrush x:Key="SemiTransparentRedBrushKey">#F0FF0000</SolidColorBrush>
<Style x:Key="TextBoxEmptyError" TargetType="{x:Type TextBox}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text.Length}" Value="0">
            <Setter Property="BorderBrush" Value="{StaticResource ResourceKey=SemiTransparentRedBrushKey}"/>
        </DataTrigger>
    </Style.Triggers>
</Style>
Run Code Online (Sandbox Code Playgroud)

我可以将文本框应用为在文本框为空时具有红色边框。太棒了,我可以添加Style="{StaticResource TextBoxEmptyError}"到控制标签中。但是,如果我想通过触发器应用此样式,以便控件仅在某些条件下使用它(例如绑定为 true),该怎么办?就像是:

<TextBox.Style>
<Style TargetType="TextBox">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=ApprovedRequired}" Value="True">
            <Setter Property="Style" Value="{StaticResource TextBoxEmptyError}"></Setter>
        </DataTrigger>
    </Style.Triggers>
</Style>
Run Code Online (Sandbox Code Playgroud)

但这段代码会抛出异常{"Style object is not allowed to affect the Style property of the object to which it applies."}

这样的事情可以做吗?

编辑:如果不能使用样式触发器来完成此操作,因为它会覆盖自身,是否有另一种方法有条件地应用资源样式?

编辑:如果此操作有更合适的术语,我可以更改问题标题。

Rac*_*hel 5

样式不能从样式内的 Setter 进行设置,因为这样第一个样式基本上将永远不会存在。

由于您正在寻找 Validation 样式,我建议您查看Validation.ErrorTemplate,尽管如果这不起作用,您可以更改触发器,以便它修改特定属性,例如 BorderBrush 而不是 Style 属性