您可以使用样式来响应 IsMouseOver 何时更改。
<Window.Resources>
<Style x:Key="RectStyle" TargetType="Rectangle">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<!-- react to property change here -->
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
然后将样式附加到元素上:
<Rectangle Style="{StaticResource RecStyle}" Width="100" Height="100" Fill="Black" />
编辑:
如果您想从样式中调用代码,则解决方案相当复杂。
首先,您必须创建一个自定义 UserControl 类并为其提供附加属性。每当附加属性发生更改时,您都可以使用属性更改回调。这是*.xaml.cs文件,保留默认的.xaml文件即可:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ExampleApp
{
/// <summary>
/// Interaction logic for MouseOverWrapper.xaml
/// </summary>
public partial class MouseOverWrapper : UserControl
{
public static readonly DependencyProperty MouseIsOverProperty;
static MouseOverWrapper()
{
MouseIsOverProperty = DependencyProperty.RegisterAttached(
"MouseIsOver", typeof(bool), typeof(MouseOverWrapper),
new FrameworkPropertyMetadata(false, OnMouseIsOverChanged));
}
public static bool GetMouseIsOver(UIElement element)
{
return (bool)element.GetValue(MouseIsOverProperty);
}
public static void SetMouseIsOver(UIElement target, bool value)
{
target.SetValue(MouseIsOverProperty, value);
}
private static void OnMouseIsOverChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// handle code here. example:
if ((bool)e.NewValue == true)
((Rectangle)d).Fill = Brushes.Yellow;
else
((Rectangle)d).Fill = Brushes.Black;
}
public MouseOverWrapper()
{
InitializeComponent();
}
}
}
然后,您必须将要响应的元素包装在自定义控件中,并使样式更改该自定义控件的附加属性。示例:
<Window x:Class="ExampleApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ExampleApp"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style x:Key="RecStyle" TargetType="Rectangle">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="local:MouseOverWrapper.MouseIsOver" Value="True" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<local:MouseOverWrapper>
<Rectangle Style="{StaticResource RecStyle}" Width="100" Height="100" Fill="Black" />
</local:MouseOverWrapper>
</Window>
将所有代码添加到OnMouseOverIsChanged 函数中,这应该可以工作。