简体   繁体   English

遍历Silverlight中的控件模板

[英]Traversing A Control Template in Silverlight

I've a control template like this 我有这样的控件模板

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

I've to traverse this control template to get the storyboard named SelectedButtonStoryboard or get the visual state SelectedButton and to invoke the either one. 我将遍历此控件模板以获取名为SelectedButtonStoryboard的故事板或获取可视状态SelectedButton并调用其中任何一个。

Please help. 请帮忙。 Thanks in advance. 提前致谢。

It sounds like you should rather change the visualstate based on your example xaml. 听起来你应该根据你的示例xaml更改visualstate。

VisualStateManager.GoToState(this, "SelectedButton", true);

Or this is you only have a reference to the control using the ControlTemplate 或者这是您只使用ControlTemplate引用控件

VisualStateManager.GoToState(controlInstance, "SelectedButton", true);

You can't name elements in a control template as there is no matching designer code-behind generated. 您无法在控件模板中命名元素,因为没有生成匹配的设计器代码隐藏。 Naming of elements works by a runtime search for names in the visual tree, and assigning member objects to them, during the InitializeObject call in a user control. 元素的命名通过运行时搜索可视树中的名称,并在用户控件中的InitializeObject调用期间为其分配成员对象来工作。

The elements in a template are effectively added to the visual tree at runtime only. 模板中的元素仅在运行时有效地添加到可视树中。

You can however use VisualTreeHelper to iterate the visual tree looking for specific element types (in your case the Storyboard objects). 但是,您可以使用VisualTreeHelper迭代可视树,查找特定的元素类型(在您的情况下是Storyboard对象)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM