我试图在一个自定义的NSButton类中编程添加一个MouseEntered事件,但我似乎无法让它启动。我正在Visual Studio for Mac中使用Xamarin.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构造函数中设置这些值,使目标是按钮而不是ViewController。将MouseEntered覆盖放在ViewController中,而不是按钮类。在按钮被添加为ViewController的子视图后创建跟踪区域。这些都没有什么不同。
任何帮助都将非常感激! 要找到Xamarin.Mac的文档相当困难......
谢谢!我想通过编程来实现Xamarin.Mac的功能。
你正在添加 Frame
作为被跟踪的区域,但您将跟踪区域附加到您创建区域的视图上,因此您需要跟踪 Bounds
的坐标。
_trackingArea = new NSTrackingArea(Bounds, NSTrackingAreaOptions.ActiveInKeyWindow | NSTrackingAreaOptions.MouseEnteredAndExited, this, null);
注意:如果你是从添加按钮的视图中进行跟踪,那么你需要跟踪 "框架",因为它的跟踪区域是相对于被跟踪的视图而言的,而不是它的子代。