5

是否可以在代码中以编程VisualState方式向CustomControl Template添加新的? 例如,我可以在设计时手动将此 XAML 添加到 CustomControl 模板:VisualStateManager

<VisualState x:Name="First">
   <Storyboard>
      <ColorAnimation Duration="0:0:0"
                      Storyboard.TargetName="SBorder"
                      Storyboard.TargetProperty="(Background).(SolidColorBrush.Color)" To="Red" />
    </Storyboard>
</VisualState>

但是我怎么能VisualState在运行时添加一个新的呢?

4

2 回答 2

2

我认为这是可行的,但绝非易事......

这应该工作:

Grid grid = this.Template.FindName("RootElement", this) as Grid;
(VisualStateManager.GetVisualStateGroups(grid)).Add(new VisualStateGroup() { /* the code for your visualstategroup here */ });

(您需要根据模板的根元素名称的类型以及设置 visualstatemanager 的位置进行调整,但所有这些都可以工作。

此外,这增加了一个新的visualStateGroup,而不仅仅是一个visualState。如果要将 VisualState 添加到现有的 visualStateGroup,则必须首先从集合中获取组,但这是常见的“从集合中获取元素”的东西

基本上:

  1. 获取包含 visualStateManager 的模板元素
  2. 使用VisualStateManager.GetVisualStateGroups()静态方法获取当前的visualStateGroups
  3. 从集合中获取您想要的组或创建一个新组并将其添加到集合中
  4. 在这个组中添加一个新的 visualState

希望这可以帮助。

于 2011-03-15T08:34:29.760 回答
1

您应该使用我建议的 XAML 创建组本身,然后您必须像这样找到您正在寻找的 VisualStateGroup:

VisualStateGroup visualStateGroupLookingFor = null;
var visualStateGroups = (VisualStateManager.GetVisualStateGroups(LayoutRoot));
foreach (VisualStateGroup state in visualStateGroups) {
    if (state.Name == "VisualStateGroupMine") {
        visualStateGroupLookingFor = state;
        break;
        }
    }

然后,你必须创建一个新的 VisualState 和 Storyboard 来添加,例如:

var visualState = new VisualState();
var storyBoard = new Storyboard();

现在,创建动画:

var animation = new DoubleAnimation();
animation.To = 10.0;

并设置动画的目标:

//assuming this is instance of class ClassFoo
//and you want to animate it's Width
Storyboard.SetTarget(animation, this);
Storyboard.SetTargetProperty(animation, new PropertyPath(ClassFoo.WidthProperty));

最后将动画添加到情节提要中,为其命名,将其添加到视觉状态组中:

storyBoard.Children.Add(animation);
visualState.Storyboard = storyBoard;
visualState.Name = "CoolNameLikeWidthAnimation";
visualStateGroupLookingFor.States.Add(visualState);

就是这样,像往常一样触发它

VisualStateManager.GoToState(this, "CoolNameLikeWidthAnimation", true);
于 2013-04-23T15:58:35.223 回答