0

我正在尝试切换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;

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

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

为什么会这样?

4

1 回答 1

0

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

Your behavior should define a boolean attached property, let's call it IsInEditMode. Then, instead of setting the template directly, set the value of the attached property to true. In your styles/templates add triggers to change templates (or set visibility for parts of the template) depending on the value of IsInEditMode.

This way you'll have ability to react to all combinations of properties (IsInEditMode && TestProperty; IsInEditMode && !TestProperty; etc...)

Also, you'll be able to use the behavior on other controls.

于 2013-10-07T10:36:03.997 回答