找不到视觉状态组

本文关键字:状态 视觉 找不到 | 更新日期: 2023-09-27 17:55:19

我有一个 UI 控件的 XAML(它继承自按钮),并且其中有各种视觉状态组,如下所示:

                            <vsm:VisualStateGroup x:Name="CommonStates">
                                <vsm:VisualState x:Name="Normal"/>
                                <vsm:VisualState x:Name="MouseOver">
                                </vsm:VisualState>
                                <vsm:VisualState x:Name="Pressed">
                                    <Storyboard>
                                        <ColorAnimation Duration="0" To="Green" Storyboard.TargetName="border" Storyboard.TargetProperty="(UIElement.Background).(SolidColorBrush.Color)" />
                                        <DoubleAnimation Duration="0" To="0.94" Storyboard.TargetName="border" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)" />
                                        <DoubleAnimation Duration="0" To="0.94" Storyboard.TargetName="border" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)" />
                                    </Storyboard>
                                </vsm:VisualState>
                                <vsm:VisualState x:Name="Disabled">
                                    <Storyboard/>
                                </vsm:VisualState>
                            </vsm:VisualStateGroup>
                            <vsm:VisualStateGroup x:Name="MyState">
                                <vsm:VisualState x:Name="Pressed_Green">
                                    <Storyboard>
                                        <ColorAnimation Duration="0" To="Yellow" Storyboard.TargetName="border" Storyboard.TargetProperty="(UIElement.Background).(SolidColorBrush.Color)" />
                                        <DoubleAnimation Duration="0" To="0.94" Storyboard.TargetName="border" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)" />
                                        <DoubleAnimation Duration="0" To="0.94" Storyboard.TargetName="border" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)" />
                                    </Storyboard>
                                </vsm:VisualState>
                            </vsm:VisualStateGroup>


                        </vsm:VisualStateManager.VisualStateGroups>

在 onapplytemplte 函数的代码隐藏中,我尝试:

VisualStateManager.GetVisualStateGroups(this).Count

但是返回值是"0",不应该是2吗?

找不到视觉状态组

VisualStateManager.VisualStateGroups 设置在控件的控件模板中的根元素上(即 this ),而不是控件本身。您需要为根元素提供一个x:Name,然后使用 GetTemplateChild 访问它。