样式触发器以应用其他样式 [英] Style Trigger to Apply another Style

查看:92
本文介绍了样式触发器以应用其他样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定,以前已经有人问过这个问题,但是我还没来得及弄清楚如何表达查询的内容。

I am sure this has been asked before, but I haven't had an easy time figuring out how to phrase the query.

我有这种风格;

<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>

我可以在文本框为空时向其申请红色边框。太好了,我可以将 Style = {StaticResource TextBoxEmptyError} 添加到控件标记中。但是,如果我想将这种样式与触发器一起使用,以便控件仅在特定条件下使用它(例如绑定为true),该怎么办?像这样的东西:

That I can apply to Textboxes to have a red border when they are empty. Its great, I can just add Style="{StaticResource TextBoxEmptyError}" to the Control Tag. But what if I want to apply this style with a trigger, so that the control only used it under certain conditions (like a binding being true)? Something like:

<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>

{不允许样式对象影响所应用对象的样式属性。}

可以这样做吗?

编辑:如果无法使用样式触发器完成此操作,因为它将覆盖自身,是否还有另一种方法

Edit: If this cannot be done with a Style trigger because it would overwrite itself, is there another way to Conditionally apply a resource style?

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

I can change the question title if there is a more proper term for this action.

推荐答案

不能从Style中的Setter设置样式,因为从本质上讲,第一个Style根本就不会存在。

Styles cannot be set from a Setter within the Style, because then essentially the first Style would never exist at all.

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

Since you're looking for a Validation style, I would recommend looking into Validation.ErrorTemplate, although if that doesn't work you can change your trigger so it modifies specific properties such as BorderBrush instead of the Style property

这篇关于样式触发器以应用其他样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆