有三种可能的解决方案:
第一个解决方案:使用 VisualSates:在 Silverlight 中更改 a Background
onMouseOver
可以通过VisualStates
. 这是一个例子:
<UserControl class="MyUserControlWithVisualStates">
<Grid x:Name="RootGrid" Background="UglyRed">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="Disabled"/>
<VisualState x:Name="MouseOver">
<Storyboard>
<ColorAnimation To="Green"
Storyboard.TargetProperty="(Background).(SolidColorBrush.Color)"
Storyboard.TargetName="RootGrid"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
<VisualStateGroup x:Name="FocusStates">
<VisualState x:Name="Focused"/>
<VisualState x:Name="Unfocused"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<OtherGridContent ... />
</Grid>
</UserControl>
和后面的代码:
public partial class MyUserControlWithVisualStates : UserControl
{
private bool m_isMouseOver;
public MyUserControlWithVisualStates()
{
InitializeComponent();
RootGrid.MouseEnter += OnRootGridMouseEnter;
RootGrid.MouseLeave += OnRootGridMouseLeave;
}
private void UpdateVisualStates()
{
if ( m_isMouseOver )
VisualStateManager.GoToState( this, "MouseOver", true );
else
VisualStateManager.GoToState( this, "Normal", true );
}
private void OnRootGridMouseLeave( object sender, MouseEventArgs e )
{
m_isMouseOver = false;
UpdateVisualStates();
}
private void OnRootGridMouseEnter( object sender, MouseEventArgs e )
{
m_isMouseOver = true;
UpdateVisualStates();
}
}
第二种解决方案:通过代码隐藏更改属性: MouseEnter 和 MouseLeave 事件处理程序只能更改网格的背景颜色。
public partial class MyUserControl : UserControl
{
private bool m_isMouseOver;
public MyUserControl()
{
InitializeComponent();
RootGrid.MouseEnter += OnRootGridMouseEnter;
RootGrid.MouseLeave += OnRootGridMouseLeave;
}
private void UpdateBackground()
{
if (m_isMouseOver)
((SolidColorBrush) RootGrid.Background).Color = Colors.Red;
else
((SolidColorBrush) RootGrid.Background).Color = Colors.Green;
}
private void OnRootGridMouseLeave( object sender, MouseEventArgs e )
{
m_isMouseOver = false;
UpdateBackground();
}
private void OnRootGridMouseEnter( object sender, MouseEventArgs e )
{
m_isMouseOver = true;
UpdateBackground();
}
}
第三种解决方案:在 xaml 中使用触发器和操作:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
<Grid x:Name="TheGrid" Background="Blue">
<Grid.Resources>
<SolidColorBrush x:Key="MouseOverBrush" Color="Green"/>
<SolidColorBrush x:Key="NormalBrush" Color="Red"/>
</Grid.Resources>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseEnter" SourceName="TheGrid">
<ei:ChangePropertyAction
TargetName="TheGrid"
PropertyName="Background"
Value="{StaticResource MouseOverBrush}"/>
</i:EventTrigger>
<i:EventTrigger EventName="MouseLeave" SourceName="TheGrid">
<ei:ChangePropertyAction
TargetName="TheGrid"
PropertyName="Background"
Value="{StaticResource NormalBrush}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Grid>