VisualStateManager无法在Universal App中使用

时间:2015-10-04 15:46:18

标签: c# xaml win-universal-app

我目前正在使用Windows通用应用,我定义了一个名为UserControl的{​​{1}}

IconButton.xaml     

IconButton

IconButton.xaml.cs

<VisualStateManager.VisualStateGroups>
    <VisualStateGroup x:Name="Common">
        <VisualState x:Name="MouseOver">
            <Storyboard>
                <ColorAnimation To="Red" Storyboard.TargetName="path" Storyboard.TargetProperty="(Fill).(SolidColorBrush.Color)" />
            </Storyboard>
        </VisualState>
    </VisualStateGroup>
</VisualStateManager.VisualStateGroups>

<Grid>
    <Path x:Name="path" Data="{x:Bind IconPathData, Mode=OneWay}" Stretch="UniformToFill" Fill="White" />
</Grid>

根据MSDNpublic sealed partial class IconButton : UserControl { public static readonly DependencyProperty IconPathDataProperty = DependencyProperty.Register("IconPathData", typeof(string), typeof(IconButton), new PropertyMetadata("")); public string IconPathData { get { return (string)GetValue(IconPathDataProperty); } set { SetValue(IconPathDataProperty, value); } } public IconButton() { InitializeComponent(); } private void UserControl_PointerEntered(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e) { VisualStateManager.GoToState(this, MouseOver.Name, true); } } 方法期望GoToState将给定名称传递给方法。在我的情况下,VisualState有一个VisualState,因此x:Name="MouseOver"应该可以找到这个。
很遗憾,GoToState始终返回false,只有在找不到具有给定名称的GoToState时才会发生这种情况。
我真的不知道该怎么做才能解决这个问题。文档非常简单,网上的几个例子和我一样,但它们让它工作 你能告诉我我做错了什么以及如何解决它?

1 个答案:

答案 0 :(得分:3)

由于您没有显示IconButton.xaml的完整内容,我认为它看起来有点像:

<UserControl
    x:Class="App1.IconButton"
    ...
    PointerEntered="UserControl_PointerEntered">

    <VisualStateManager.VisualStateGroups>
        ...
    </VisualStateManager.VisualStateGroups>

    <Grid>
        <Path ... />
    </Grid>
</UserControl>

如果是这样,请将VisualStateManager移到Grid内(成为UserControl的孩子:

<UserControl
    x:Class="App1.IconButton"
    ...
    PointerEntered="UserControl_PointerEntered">

    <Grid>
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="Common">
                <VisualState x:Name="MouseOver">
                    <Storyboard>
                        <ColorAnimation To="Red" Storyboard.TargetName="path" Storyboard.TargetProperty="(Fill).(SolidColorBrush.Color)" />
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>

        <Path x:Name="path" ... />
    </Grid>
</UserControl>