monomac / Xamarin.Mac - 使用NSTextViewDelegate派生的NSTextField

时间:2013-02-22 14:00:30

标签: mono monomac xamarin xamarin.mac

在objective-C中,我可以使我的NSTextField子类符合NSTextViewDelegate协议 - 就像这样:

@interface PasswordField : NSTextField <NSTextViewDelegate>

如何将这个成语翻译成C#/ monomac?

我尝试过子类化NSTextViewDelegate:

private class TextViewDelegate : NSTextViewDelegate
{}

并将其分配给我的NSTextField子类的delegate属性:

public class PasswordField : NSTextField
{
    public PasswordField(NSCoder coder) : base(coder)
    {
        this.Delegate = new TextViewDelegate();
    }
}

但是,显然这不起作用,因为 NSTextField Delegate 属性(正确地)键入为 NSTextFieldDelegate

Error CS0029: Cannot implicitly convert type `PasswordFieldControl.PasswordField.TextViewDelegate' to `MonoMac.AppKit.NSTextFieldDelegate' (CS0029)

那么如何使这个工作像在Objective-C中那样工作?

1 个答案:

答案 0 :(得分:1)

有两种方法可以做到这一点:

如果您将代表分开,可以这样做:

class TextViewDelegate : NSTextViewDelegate
{
    public override void TextDidChange (NSNotification notification)
    {
    }
}

public class PasswordField : NSTextField
{
    public PasswordField(NSCoder coder) : base(coder)
    {
        this.WeakDelegate = new TextViewDelegate();
    }
}

或者,如果你想使用相同的PasswordField对象:

public class PasswordField : NSTextField
{
    [Export("textDidChange:")]
    public void TextDidChange (NSNotification notification)
    {
    }

    public PasswordField(NSCoder coder) : base(coder)
    {
        this.WeakDelegate = this;
    }
}