5

カスタムコントロールテンプレートのプログラムにコードで新しいVisualStateものを追加することは可能ですか? たとえば、この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 をセットアップした場所に応じて調整する必要がありますが、全体としては機能します。

また、これにより、visualState だけでなく、新しい visualStateGroup が追加されます。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));

最後に、アニメーションをストーリーボードに追加し、名前を付けて、visualstategroup に追加します。

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 に答える