WPF - 创建触发器以使用资源样式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21855827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 10:54:31  来源:igfitidea点击:

WPF - creating a trigger to use a resource style

c#wpf

提问by user3323660

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

我有一个带按钮的对话框 - 按钮文本和功能是动态的,并且会根据用户的需要而变化。在大多数情况下,按钮样式是默认样式,如果按钮是 OK 按钮,我希望按钮使用不同的样式。我尝试添加一个触发器,该触发器将根据布尔属性更改按钮样式:(当 IsOKButton=true 时使用“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.
  • RedButtonStyle 是一种资源样式,可用于不同项目的不同按钮类型,因此灵魂应该在我的项目中,不能在资源样式本身中。

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

但是当使用这个触发器时,我得到了一个例外。“设置属性 system.windows.controls.control.template 抛出异常”

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

谁能帮我解决这个问题,或者提出一个动态设置样式的想法?

Thanks

谢谢

回答by TylerD87

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.

然后从一开始就为您的按钮设置 OKButtonStyle 样式。

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:

如果想让您的 OK 按钮与您希望所有按钮都具有的更通用的样式大致相同,您可以将它基于这样的通用样式:

<Style x:Key="OKButtonStyle" BasedOn="{StaticResource GeneralButtonStyle}">