VisualStateManager 中的状态名称有意义吗?

Do the names of states in a VisualStateManager have meaning?

VisualStateManager 中的状态和 VisualStateGroup 的名称是任意的,还是具有更深的含义?

它们在某些方面看起来类似于 CSS 中的伪 类(ButtonCommonStatesNormalPointerOverPressedDisabled,而 CSS 具有 :hover:active 和定位禁用控件的方法)。但它们也不同——Checkbox 有(似乎)completely different statesCheckedUncheckedIndeterminate.

在开发应用程序时,我如何知道哪些 VisualStates 可用?如果我使用错误的名称会怎样?

州名是否有更深的含义?

Are the names for states and VisualStateGroups in VisualStateManager arbitrary, or do they have deeper meaning?

状态和VisualStateGroup的名称确实是随意的,但它们确实具有更深的含义。

VisualStates in VisualStateManager are [representations of] the visual appearance of a UI element when it is in a specific state. They use Storyboards or Setters to represent arbitrary changes to a given Control (for example, make the background red). Control authors can call VisualStateManager.GoToState 在他们的代码隐藏中激活一个命名的 VisualState。

这样,VisualState 名称是任意的:我可以创建一个名为 CitelaosGreatState 的 VisualState 并通过调用 GoToState(this, "CitelaosGreatState") 激活它。这就是为什么名称如此多样的原因——按钮有您提到的 CommonStates,而复选框有完全不同的名称。

但是,出于实际目的,您选择的 VisualState 名称不是任意的

如果您正在使用 VisualStateManager modify the look & feel of a default control (by overriding the ControlTemplate), you almost certainly want to pick VisualState and VisualStateGroup names that correspond exactly to the names in the original ControlTemplate (which you can find in the XAML designer or )。这是一个功能问题:例如,Button 的实现者为悬停 Button 时出现的 VisualState 选择了一个任意名称 - CommonStates PointerOver。他们的代码隐藏中处理悬停 Button 调用的逻辑 GoToState(this, "PointerOver") (或某些等效项)。如果要自定义该外观,则必须提供具有该名称的 VisualState。

你当然可以 提供一个名为 CitelaosGreatState 甚至 Hover 的酷状态,但如果代码隐藏从不调用 GoToState同样的字符串,无论名称如何,您的状态都不会被激活。

当然,这意味着对于完全自定义的控件(您可以控制 VisualStateManager VisualStateManager.GoToState 的调用),您可以命名您的状态随便你!

我怎么知道选择哪些名称?

As I develop my apps, how do I know which VisualStates are available?

  • 完全自定义控件:如上所述,如果您同时编写 VisualStateManager 和对 VisualStateManager.GoToState 的调用,请随意命名 VisualStates!如果您定义了一个名为 State1 的状态,您可以在代码隐藏中使用 GoToState State1.
  • 激活它
  • 现有控件的自定义模板:如果您正在重新模板化现有控件(使用ControlTemplate),您应该选择与该控件上的现有状态相匹配的名称。例如,Button 定义 CommonStatesHoveredPointerOverPressedDisabled。定义那些。具有其他名称的状态将永远不会被激活(因为 XAML 团队编写的代码隐藏永远不会使用该名称的 GoToState)。了解现有状态—

如何知道控件的现有 VisualStates?

  1. 为您的控件(如前所述,您可以在 XAML 设计器或).
  2. 使用模板 VisualStateGroup 中的名称。

名字有误?

What happens if I use the wrong names?

由于名称是任意的,“错误的名称”不是这里最清楚的问题。看两种情况比较容易:

  • 您定义了一个 VisualState,代码隐藏从不使用 GoToState 激活(例如,您将一个名为 CitelaosGreatStateHover 的状态添加到按钮的自定义模板中):没有什么可怕的事情发生,但是你的状态永远不会被激活。
  • 您未能定义代码隐藏试图激活的 VisualState(例如,您为自定义按钮模板添加了不完整的 VisualStateGroup):GoToState 调用无效。