开发者

Style Trigger to Apply another Style

开发者 https://www.devze.com 2023-04-07 09:38 出处:网络
I am sure this has been asked before, but I haven\'t had an easy time figuring out how to phrase the query.

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

I have this style;

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

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>

This code throws an exception though {"Style object is not allowed to affect the Style property of the object to which it applies."}

Can something like this be done?

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?

Edit: I can change the question title if there is a mo开发者_运维技巧re proper term for this action.


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

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


i would think of using a Template with a TemplateTrigger and there you can change the style to what ever you like based on what ever condition

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号