【问题标题】:Triggering template in style is not working after changing template in code更改代码中的模板后,样式中的触发模板不起作用
【发布时间】:2013-10-02 16:23:34
【问题描述】:

我正在尝试切换样式中的按钮的ControlTemplate

<Style TargetType="Button">
      <Style.Triggers>
          <DataTrigger Binding="{Binding Path=TestProperty}" Value="true">
                <Setter Property="Template" Value="{StaticResource MyCustomTemplate}"/>
           </DataTrigger>
       </Style.Triggers>
</Style>

在我在代码中更改按钮的模板之前,它工作正常。例如,

myButton.Template = someTemplate;

即使这样也足以重现错误:

myButton.Template = myButton.Template;

顺便说一下,下面的代码将正确地将myButton 前景更改为Aqua。这意味着触发器工作正常。它只是不能设置模板

<Style TargetType="Button">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=TestProperty}" Value="true">
            <Setter Property="Template" Value="{StaticResource MyCustomTemplate}"/>
            <Setter Property="Foreground" Value="Aqua"></Setter>
        </DataTrigger>
    </Style.Triggers>
</Style>

为什么会这样?

【问题讨论】:

  • 您是否也在按钮本身上设置了模板?
  • 按钮有它的默认模板。并且没有设置myButton.Template = myButton.Template 触发器可以正常工作。
  • 如果您直接设置 myButton.Template(作为本地值),则样式值无法覆盖它。见Dependency Property Value Precedence
  • @LPL 有没有办法从代码和样式中操作控件的模板。我需要这个,因为我正在使用 MVVM 模式并希望我的控件根据 ViewModel 中的某些属性触发其模板。另一方面,我需要将更改模板的行为附加到 TextBox 并返回以允许一些编辑选项。
  • 你为什么要在代码隐藏中设置模板...我想知道你在什么条件下在代码隐藏中更改它..为了使它工作..你必须使用触发器来做到这一点

标签: c# wpf triggers styles controltemplate


【解决方案1】:

正如问题 cmets 中提到的,使用 MVVM 并更改代码中的控件是一个坏主意。

您的行为应该定义一个布尔附加属性,我们称之为IsInEditMode。然后,不是直接设置模板,而是将附加属性的值设置为true。在您的样式/模板中添加触发器以更改模板(或设置模板部分的可见性),具体取决于 IsInEditMode 的值。

这样您就可以对所有属性组合做出反应(IsInEditMode &amp;&amp; TestPropertyIsInEditMode &amp;&amp; !TestProperty;等等...)

此外,您还可以在其他控件上使用该行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多