【发布时间】:2019-09-06 03:44:57
【问题描述】:
当光标悬停在一个元素上时,我想动态改变它的样式。
我知道对于Control,我可以使用ControlTemplate 和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);
}
}
但是,以上代码只适用于Control类,必须使用C#代码,在某些情况下不方便。
例如,我在下面的代码中有一个Grid,当光标悬停在它上面时,我想将其背景颜色更改为蓝色,我可以只使用 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>
【问题讨论】: