我有一个这样的控件模板
<ControlTemplate TargetType="Button">
<Grid >
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualStateGroup.Transitions>
<!--Take one half second to trasition to the MouseOver state.-->
<VisualTransition To="MouseOver"
GeneratedDuration="0:0:0.5"/>
</VisualStateGroup.Transitions>
<VisualState x:Name="Normal" />
<!--Change the SolidColorBrush, ButtonBrush, to red when the
mouse is over the button.-->
<VisualState x:Name="MouseOver">
<Storyboard>
<ColorAnimation Storyboard.TargetName="ButtonBrush"
Storyboard.TargetProperty="Color" To="Red" />
</Storyboard>
</VisualState>
**<VisualState x:Name="SelectedButton">
<Storyboard x:Name="SelectedButtonStoryboard">
<ColorAnimation Storyboard.TargetName="ButtonBrush"
Storyboard.TargetProperty="Color" To="Red" />
</Storyboard>
</VisualState>**
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid.Background>
<SolidColorBrush x:Name="ButtonBrush" Color="Green"/>
</Grid.Background>
</Grid>
</ControlTemplate>
我必须遍历这个控件模板以获得名为SelectedButtonStoryboard
的故事板或获得视觉状态SelectedButton
并调用其中任何一个。
请帮助。
听起来您应该根据示例xaml更改visualstate。
VisualStateManager.GoToState(this, "SelectedButton", true);
或者你只能使用ControlTemplate
来引用控件VisualStateManager.GoToState(controlInstance, "SelectedButton", true);
控件模板中不能命名元素,因为没有生成匹配的设计器代码。元素的命名是通过在运行时搜索可视树中的名称,并在用户控件中的InitializeObject调用期间为它们分配成员对象来实现的。
模板中的元素仅在运行时有效地添加到可视化树中。
你可以使用VisualTreeHelper来迭代可视化树来寻找特定的元素类型(在你的例子中是Storyboard对象)。