有没有简单的方法来处理Click
事件没有两个回调在Grid
。但是我们可以编写一些帮助代码来实现它。
这是你可以使用我的助手代码:以上
<Grid Background="Transparent">
<local:RoutedEventExtension.Event>
<local:ClickEvent Click="Grid_Click"></local:ClickEvent>
</local:RoutedEventExtension.Event>
</Grid>
XAML。
private void Grid_Click(object sender, EventArgs e)
{
// Write your event handler code here.
}
C#以上。
这是我的助手代码:
public abstract class RoutedEventExtension
{
public static readonly DependencyProperty EventProperty = DependencyProperty.RegisterAttached(
"Event", typeof(RoutedEventExtension), typeof(RoutedEventExtension),
new PropertyMetadata(null, OnEventChanged));
public static void SetEvent(DependencyObject element, RoutedEventExtension value)
{
element.SetValue(EventProperty, value);
}
public static RoutedEventExtension GetEvent(DependencyObject element)
{
return (RoutedEventExtension) element.GetValue(EventProperty);
}
private static void OnEventChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is IInputElement element))
{
throw new InvalidOperationException("RoutedEventExtension can only be attached on an IInputElement.");
}
var oldValue = (RoutedEventExtension) e.OldValue;
var newValue = (RoutedEventExtension) e.NewValue;
oldValue?.Detach();
newValue.Attach(element);
}
protected IInputElement Target { get; private set; }
private void Attach(IInputElement target)
{
Target = target;
OnAttached();
}
private void Detach()
{
try
{
OnDetaching();
}
finally
{
Target = null;
}
}
protected abstract void OnAttached();
protected abstract void OnDetaching();
}
public sealed class ClickEvent : RoutedEventExtension
{
public event EventHandler Click;
protected override void OnAttached()
{
Target.MouseLeftButtonDown += OnMouseLeftButtonDown;
Target.MouseLeftButtonUp += OnMouseLeftButtonUp;
Target.LostMouseCapture += OnLostMouseCapture;
}
protected override void OnDetaching()
{
Target.MouseLeftButtonDown -= OnMouseLeftButtonDown;
Target.MouseLeftButtonUp -= OnMouseLeftButtonUp;
Target.LostMouseCapture -= OnLostMouseCapture;
}
private bool _isMouseDown;
private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
_isMouseDown = true;
Mouse.Capture(Target);
}
private void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (!_isMouseDown)
{
return;
}
Mouse.Capture(null);
OnClick();
}
private void OnLostMouseCapture(object sender, MouseEventArgs e)
{
_isMouseDown = false;
}
private void OnClick()
{
Click?.Invoke(this, EventArgs.Empty);
}
}
助手代码包含两个班。一种提供一种常见的方式来附加IInputElement
上的任何事件,另一种提供基本的Click
实现。
您可以通过继承自RoutedEventExtension
自己编写自己的其他事件实现。
你有代码示例,所以这种行为可以被复制? –
@GingerNinja添加了一个片段 – John
那么你的XAML,网格等等。能够看到问题是否可以被复制将是很好的。 –