Имитация эффекта наведения мыши на fontIcon в uwp

В настоящее время я работаю над проектом uwp, в котором используется гамбургер-меню. Пока я создал меню, используя этот код

<FontIcon FontFamily="Segoe MDL2 Assets" Glyph="&#xE700;"
                      Foreground="Black" VerticalAlignment="Center" Margin="12,0,8,0">

Чего я действительно хочу добиться, так это того, что при наведении курсора мыши на значок ожидается изменение цвета фона меню гамбургера. Это похоже на кнопку свертывания в приложении Windows. После поиска в API я понял, что не было никакого события наведения мыши, и я думаю, что ближе всего к нему было событие PointerEnetered. Как мне добиться этого с помощью события PointerEntered в XAML?


person Tolani    schedule 27.03.2016    source источник
comment
Посмотрите это меню «Гамбургер» видео, оно может быть мне полезным.   -  person Sender    schedule 13.06.2016


Ответы (2)


В дополнение к решению, которое было опубликовано @Archana для изменения цвета переднего плана FontIcon, для изменения цвета фона меню гамбургера и для того, чтобы он был похож на кнопку сворачивания в приложении Windows, мы можем попытаться добавить FontIcon xaml в содержимое кнопки и измените цвет фона кнопки, чтобы он выглядел так, будто мы изменили цвет фона меню гамбургера.

Для обработки события наведения мыши, как вы сказали, нам нужно использовать файл PointerEnetered. Но не забудьте обработать PointerExited, чтобы цвет фона меню гамбургера вернулся к нормальному после того, как мы не перемещайте мышь по гамбургер-меню.

Для получения дополнительной информации, пожалуйста, проверьте мой образец:

XAML-код:

 <SplitView.Pane>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <StackPanel Grid.Row="0" Height="auto">
                    <Button BorderThickness="0" Background="Transparent" PointerEntered="Button_PointerEntered" PointerExited="Button_PointerExited">
                        <Button.Content>
                            <FontIcon FontFamily="Segoe MDL2 Assets" Glyph="&#xE700;"
                  Foreground="Black" VerticalAlignment="Center" Margin="12,0,8,0"/>
                        </Button.Content>
                    </Button>
                </StackPanel>
                <StackPanel Grid.Row="1">
                 //add other icon
                </StackPanel>
            </Grid>
        </SplitView.Pane>

Код СС:

private void Button_PointerEntered(object sender, PointerRoutedEventArgs e)
    {
        Button test = sender as Button;
        test.Background = new SolidColorBrush(Colors.Red);
    }

    private void Button_PointerExited(object sender, PointerRoutedEventArgs e)
    {
        Button test = sender as Button;
       test.Background = new SolidColorBrush(Colors.Transparent);
    }

Если вы хотите реализовать его только с помощью XAML, щелкните правой кнопкой мыши кнопку, чтобы изменить стиль кнопки и изменить цвет фона кнопки внутри PointerOver VisualState следующим образом:

 <VisualState x:Name="PointerOver">
             <Storyboard>
                  <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="RootGrid">
                         <DiscreteObjectKeyFrame KeyTime="0" Value="Red"/>
                   </ObjectAnimationUsingKeyFrames>
                                                                          </Storyboard>
</VisualState>

Для завершенного кода XAML проверьте:

 <Page.Resources>
    <Style x:Key="ButtonStyle1" TargetType="Button">
        <Setter Property="Background" Value="{ThemeResource SystemControlBackgroundBaseLowBrush}"/>
        <Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseHighBrush}"/>
        <Setter Property="BorderBrush" Value="{ThemeResource SystemControlForegroundTransparentBrush}"/>
        <Setter Property="BorderThickness" Value="{ThemeResource ButtonBorderThemeThickness}"/>
        <Setter Property="Padding" Value="8,4,8,4"/>
        <Setter Property="HorizontalAlignment" Value="Left"/>
        <Setter Property="VerticalAlignment" Value="Center"/>
        <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
        <Setter Property="FontWeight" Value="Normal"/>
        <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
        <Setter Property="UseSystemFocusVisuals" Value="True"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid x:Name="RootGrid" Background="{TemplateBinding Background}">
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal">
                                    <Storyboard>
                                        <PointerUpThemeAnimation Storyboard.TargetName="RootGrid"/>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="PointerOver">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="RootGrid">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="Red"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ContentPresenter">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseMediumLowBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseHighBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <PointerUpThemeAnimation Storyboard.TargetName="RootGrid"/>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Pressed">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="RootGrid">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlBackgroundBaseMediumLowBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ContentPresenter">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightTransparentBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseHighBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <PointerDownThemeAnimation Storyboard.TargetName="RootGrid"/>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Disabled">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="RootGrid">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlBackgroundBaseLowBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseMediumLowBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ContentPresenter">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledTransparentBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <ContentPresenter x:Name="ContentPresenter" AutomationProperties.AccessibilityView="Raw" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" ContentTemplate="{TemplateBinding ContentTemplate}" ContentTransitions="{TemplateBinding ContentTransitions}" Content="{TemplateBinding Content}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Padding="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Page.Resources>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <SplitView.Pane>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <StackPanel Grid.Row="0" Height="auto">
                    <Button BorderThickness="0" Background="Transparent" Style="{StaticResource ButtonStyle1}" PointerEntered="Button_PointerEntered" PointerExited="Button_PointerExited">
                        <Button.Content>
                            <FontIcon FontFamily="Segoe MDL2 Assets" Glyph="&#xE700;"
                  Foreground="Black" VerticalAlignment="Center" Margin="12,0,8,0"/>
                        </Button.Content>
                    </Button>
                </StackPanel>
                <StackPanel Grid.Row="1">
                 //add other icon
                </StackPanel>
            </Grid>
        </SplitView.Pane>

    </Grid>
</Grid>

Результат:

введите здесь описание изображения

Спасибо.

person Amy Peng - MSFT    schedule 28.03.2016

Обновить Вы не можете сделать это в XAMl. Если вы хотите сделать это в XAMl, вместо этого используйте кнопку и отредактируйте визуальное состояние кнопки.

 <Button Foreground="Black" Style="{StaticResource ButtonStyle1}">
                <FontIcon FontFamily="Segoe MDL2 Assets" Glyph="&#xE700;" 
     VerticalAlignment="Center" Margin="12,0,8,0"/>
            </Button>

 <Style x:Key="ButtonStyle1" TargetType="Button">
            <Setter Property="Background" Value="{ThemeResource SystemControlBackgroundBaseLowBrush}"/>
            <Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseHighBrush}"/>
            <Setter Property="BorderBrush" Value="{ThemeResource SystemControlForegroundTransparentBrush}"/>
            <Setter Property="BorderThickness" Value="{ThemeResource ButtonBorderThemeThickness}"/>
            <Setter Property="Padding" Value="8,4,8,4"/>
            <Setter Property="HorizontalAlignment" Value="Left"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
            <Setter Property="FontWeight" Value="Normal"/>
            <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
            <Setter Property="UseSystemFocusVisuals" Value="True"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Grid x:Name="RootGrid" Background="{TemplateBinding Background}">
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                    <VisualState x:Name="Normal">
                                        <Storyboard>
                                            <PointerUpThemeAnimation Storyboard.TargetName="RootGrid"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="PointerOver">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ContentPresenter">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseMediumLowBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="White"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <PointerUpThemeAnimation Storyboard.TargetName="RootGrid"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="Pressed">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="RootGrid">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlBackgroundBaseMediumLowBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ContentPresenter">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightTransparentBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseHighBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <PointerDownThemeAnimation Storyboard.TargetName="RootGrid"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="Disabled">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="RootGrid">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlBackgroundBaseLowBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseLowBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ContentPresenter">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledTransparentBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>
                            <ContentPresenter x:Name="ContentPresenter" AutomationProperties.AccessibilityView="Raw" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" ContentTemplate="{TemplateBinding ContentTemplate}" ContentTransitions="{TemplateBinding ContentTransitions}" Content="{TemplateBinding Content}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Padding="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

Вы можете сделать так

     <FontIcon FontFamily="Segoe MDL2 Assets" Glyph="&#xE700;" PointerPressed="FontIcon_PointerPressed" PointerEntered="FontIcon_PointerEntered"
    PointerExited="FontIcon_PointerExited"    Foreground="Black" VerticalAlignment="Center" Margin="12,0,8,0"/>

   private void FontIcon_PointerPressed(object sender, PointerRoutedEventArgs e)
        {
            (sender as FontIcon).Foreground = new SolidColorBrush(Colors.White);
        }

        private void FontIcon_PointerEntered(object sender, PointerRoutedEventArgs e)
        {
            (sender as FontIcon).Foreground = new SolidColorBrush(Colors.White);
        }

        private void FontIcon_PointerExited(object sender, PointerRoutedEventArgs e)
        {
            (sender as FontIcon).Foreground = new SolidColorBrush(Colors.Black);
        }
person Archana    schedule 28.03.2016