macos - 如何在 MacOS 和/或 UWP 的 Xamarin.Forms 按钮上实现悬停事件?
问题描述
我有一个针对 MacOS 和 WPF 以及其他平台的 Xamarin.Forms 项目。对于 MacOS 和 UWP,我需要知道鼠标何时悬停在按钮上,以便向用户显示工具提示。但是,默认的 Xamarin.Forms 按钮不包含 MouseOver或类似的东西。我知道这不是移动设备的优先事项,但是有没有办法为 UWP 和 MacOS 实现这一点?
我是否必须使用自定义渲染器,如果是这样,是否有人有 MacOS/UWP 的自定义渲染示例,可以让我知道鼠标何时悬停在按钮上?
解决方案
如何在 UWP 的 Xamarin.Forms 按钮上实现悬停事件?
根据您的要求,您可以使用Effect来实现此功能。首先,我们需要制作MouseOverEffect
并添加MouseOver
Action 类型的附加属性。
public static class MouseOverEffect
{
public static readonly BindableProperty MouseOverProperty =
BindableProperty.CreateAttached("MouseOver", typeof(Action), typeof(MouseOverEffect), default(Action), propertyChanged: OnhandlerChanged);
public static Action GetMouseOver(BindableObject view)
{
return (Action)view.GetValue(MouseOverProperty);
}
public static void SetMouseOver(BindableObject view, Action value)
{
view.SetValue(MouseOverProperty, value);
}
static void OnhandlerChanged(BindableObject bindable, object oldValue, object newValue)
{
var view = bindable as View;
if (view == null)
{
return;
}
Action action = (Action)newValue;
if (action != null)
{
view.Effects.Add(new ControlTooltipEffect());
}
else
{
var toRemove = view.Effects.FirstOrDefault(e => e is ControlTooltipEffect);
if (toRemove != null)
{
view.Effects.Remove(toRemove);
}
}
}
class ControlTooltipEffect : RoutingEffect
{
public ControlTooltipEffect() : base($"Microsoft.{nameof(MouseOverEffect)}")
{
}
}
}
然后做IWP客户端Effect实现
获得附加按钮控制和监听PointerEntered
,当指针输入时调用动作方法。
[assembly: ResolutionGroupName("Microsoft")]
[assembly: ExportEffect(typeof(UWPMouseEffect), nameof(MouseOverEffect))]
namespace NavigateTest.UWP
{
public class UWPMouseEffect : PlatformEffect
{
protected override void OnAttached()
{
var control = Control ?? Container;
if (control is FormsButton)
{
control.PointerEntered += Control_PointerEntered;
}
}
private void Control_PointerEntered(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
{
var action = MouseOverEffect.GetMouseOver(Element);
action();
}
protected override void OnDetached()
{
}
}
}
用法
<Button
effect:MouseOverEffect.MouseOver="{Binding MouseOverAction}"
Clicked="Button_Clicked"
Text="Next"
/>
视图模型
public class Page2ViewModel : INotifyPropertyChanged, IDisposable
{
public Page2ViewModel()
{
MouseOver(() =>
{
// do some sth
});
}
public Action MouseOverAction { set; get; }
public void MouseOver(Action action)
{
MouseOverAction = action;
}
}
推荐阅读
- python - 如何通过 Outlook 将 HTML 文件作为表格发送?
- php - 将当前 URL 重写为不同文件夹中的相似 URL
- python - Python空闲到python.exe
- javascript - SoundCloud 的客户端 ID
- html - 相邻前置内的“锚定”按钮
- javascript - 将显示更改为隐藏时如何阻止功能重复
- java - optaplanner-spring-boot-starter vs kie-server-spring-boot-starter
- javascript - 如果网格列为空,则使内容跨度或网格折叠
- ios - 找不到 UnityAppController.h 文件
- scala - 如何匹配列表元素