【发布时间】:2020-05-07 14:06:23
【问题描述】:
我正在尝试以编程方式将 MouseEntered 事件添加到自定义 NSButton 类,但我似乎无法触发它。我正在使用 Xamarin.Mac 在 Visual Studio for Mac 中编写一个 Mac OS 应用程序。我需要在代码中添加事件,因为我正在动态创建按钮。
这是创建这些按钮的 ViewController。它们在靠近底部的 DrawHexMap 方法中实例化。
public partial class MapController : NSViewController
{
public MapController (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
DrawHexMap();
}
partial void GoToHex(Foundation.NSObject sender)
{
string[] coordinateStrings = ((NSButton)sender).Title.Split(',');
Hex chosenHex = HexRepo.GetHex(coordinateStrings[0], coordinateStrings[1]);
HexService.currentHex = chosenHex;
NSTabViewController tp = (NSTabViewController)ParentViewController;
tp.TabView.SelectAt(1);
}
private void DrawHexMap()
{
double height = 60;
for (int x = 0; x < 17; x++) {
for (int y = 0; y < 13; y++) {
HexButton button = new HexButton(x, y, height);
var handle = ObjCRuntime.Selector.GetHandle("GoToHex:");
button.Action = ObjCRuntime.Selector.FromHandle(handle);
button.Target = this;
View.AddSubview(button);
}
}
}
}
这是自定义按钮类。
public class HexButton : NSButton
{
public NSTrackingArea _trackingArea;
public HexButton(int x, int y, double height)
{
double width = height/Math.Sqrt(3);
double doubleWidth = width * 2;
double halfHeight = height/2;
double columnNudge = decimal.Remainder(x, 2) == 0 ? 0 : halfHeight;
Title = x + "," + y;
//Bordered = false;
//ShowsBorderOnlyWhileMouseInside = true;
SetFrameSize(new CGSize(width, height));
SetFrameOrigin(new CGPoint(width + (x * doubleWidth), (y * height) + columnNudge));
_trackingArea = new NSTrackingArea(Frame, NSTrackingAreaOptions.ActiveInKeyWindow | NSTrackingAreaOptions.MouseEnteredAndExited, this, null);
AddTrackingArea(_trackingArea);
}
public override void MouseEntered(NSEvent theEvent)
{
base.MouseEntered(theEvent);
Console.WriteLine("mouse enter");
}
}
如您所见,我正在为按钮创建一个跟踪区域并将其添加到构造函数中。然而,我似乎无法让 MouseEntered 开火。我知道此类中的 MouseEntered 覆盖有效,因为当我直接从我的代码中调用 button.MouseEntered() 时,该方法会触发。
我尝试过的其他一些事情包括:注释掉在 ViewController 中设置 Action 和 Target 的行,以防它们以某种方式覆盖 MouseEntered 处理程序。在 HexButton 构造函数中设置这些值,以便 Target 是按钮而不是 ViewController。将 MouseEntered 覆盖放在 ViewController 而不是按钮类中。在将按钮作为子视图添加到 ViewController 后创建跟踪区域。这些都没有影响。
任何帮助将不胜感激!很难找到 Xamarin.Mac 的文档...
谢谢!
【问题讨论】:
-
@SushiHangover 我没有,但我只是添加了它,不幸的是它没有任何区别。
标签: xamarin cocoa xamarin.mac