3

我有一个在模式 A 中具有样式模板的按钮。在模式 A 中,此按钮具有 PointerOver VisualState。当我处于模式 B 时,我使用相同的按钮,但在模式 B 中,我希望有一个不同的 PointerOver VisualState。

利用视觉状态完成这样的事情的最佳方法是什么?我正在考虑为同一个按钮设置两个不同的样式模板,并以某种方式更改要在后面的代码中使用的样式模板,但不确定这是否可行,或者这是否是解决此问题的最佳方法。

有什么建议么?

4

2 回答 2

2

在后面的代码中试试这个:

[control name].Style = this.FindResource("[style key]") as Style;

另外,您不应该将样式称为“样式模板”,因为我可能会误解它。样式和模板是两个不同的东西。

  • 模板定义了给定控件的构建方式。例如,如果 aButton是使用 aBorder和 a构建的TextBlock(或使用其他一些控件)。
  • 样式定义了一组属性,描述了给定控件的外观(模板是其中一个属性)。
于 2017-10-11T08:44:23.223 回答
1

另一种选择是使用 aConverter来决定应该是Style哪个。Button

转换器:

public class ButtonStyleConverter : IValueConverter {
  public object Convert(object value, Type targetType, object parameter, string language)
  {
    var mode = (int)value;
    return mode == 1 ? Application.Current.Resources["ButtonStyle1"] as Style : Application.Current.Resources["ButtonStyle2"] as Style;
  }

  public object ConvertBack(object value, Type targetType, object parameter, string language)
  {
  //Do nothing
  }
}

用法:

<Button Content="Hello" Style="{Binding Button1Mode, Converter={StaticResource ButtonStyleConverter}}"/>
<Button Content="World" Style="{Binding Button2Mode, Converter={StaticResource ButtonStyleConverter}}" />

我在我的 ViewModel 上使用了Binding一个属性,理论上它可以让您根据数据修改按钮在运行时的“模式”。如果您需要更多代码,我很乐意在 Github 上发布一个示例。

于 2017-10-13T16:37:07.087 回答