When the cursor hovers over an element, I want to change its style dynamically.
I know that for a Control
, I can do this using ControlTemplate
and VisualStateManager
.
<Page
x:Class="World.BlankPage1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:World"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.Resources>
<ControlTemplate x:Key="ControlTemplate" TargetType="ContentControl">
<Grid x:Name="RootGrid" Width="100" Height="100" Background="Red" PointerEntered="RootGrid_PointerEntered" PointerExited="RootGrid_PointerExited">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState x:Name="Normal"/>
<VisualState x:Name="Active">
<VisualState.Setters>
<Setter Target="RootGrid.Background" Value="Blue"/>
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Grid>
</ControlTemplate>
</Page.Resources>
<Grid>
<ContentControl Template="{StaticResource ControlTemplate}"/>
</Grid>
</Page>
public sealed partial class BlankPage1 : Page {
public BlankPage1() {
this.InitializeComponent();
}
private void RootGrid_PointerEntered(object sender,PointerRoutedEventArgs e) {
if (VisualTreeHelper.GetParent((Grid)sender) is ContentControl control) VisualStateManager.GoToState(control,"Active",false);
}
private void RootGrid_PointerExited(object sender,PointerRoutedEventArgs e) {
if (VisualTreeHelper.GetParent((Grid)sender) is ContentControl control) VisualStateManager.GoToState(control,"Normal",false);
}
}
However, the above code only applies to Control
classes and must use C# code, which is inconvenient for some situations.
For example, I have a Grid
in the following code, and when the cursor hovers over it, I want to change its background color to blue, can I do this using only XAML?
<Page
x:Class="World.BlankPage1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<Grid Width="100" Height="100" Background="Red"/>
</Grid>
</Page>