Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - creating a trigger to use a resource style

Tags:

c#

wpf

I have a dialog with buttons - the buttons text and functionality are dynamic and changing according to the user's needs. In most cases the button style is the default style, in case the button is an OK button, I would like the button to use a different style. I've tried to add a trigger that will change the button style according to a Boolean property: (when IsOKButton=true use the "RedButtonStyle")

 <Button.Template>
                <ControlTemplate >
                    <ControlTemplate.Triggers>
                        <DataTrigger Binding="{Binding IsOKButton}" Value="True">
                            <Setter Property="Style" Value="{StaticResource RedButtonStyle}"/>
                        </DataTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Button.Template>  
  • the RedButtonStyle is a resource style that can be used in diffrent projects for a diffrent buttons type , so the soultion should be in my project and can't be in the resource style itself.

But when using this trigger I get an exception. "set property system.windows.controls.control.template threw an exception"

Can anyone help me resolve this problem, or suggest an idea to set the style dynamicly?

Thanks

like image 905
user3323660 Avatar asked Oct 29 '25 12:10

user3323660


1 Answers

You could put the trigger in the style itself:

<Style x:Key="OKButtonStyle">
    <Style.Triggers>
        <DataTrigger Binding="{Binding IsOKButton}" Value="True">
            //Whatever Property is different in the OKButtonStyle
        </DataTrigger>
        <DataTrigger Binding="{Binding IsOKButton}" Value="False">
            //Set it back to default
        </DataTrigger>
    </Style.Triggers>
</Style>

Then just give your button the style OKButtonStyle from the start.

If want to make your OK Button mostly the same as a more general style which you want all your buttons to have you can just base it on the general one like this:

<Style x:Key="OKButtonStyle" BasedOn="{StaticResource GeneralButtonStyle}">
like image 105
TylerD87 Avatar answered Oct 31 '25 02:10

TylerD87



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!