Search code examples
c#xamarinnstextfield

How can I check if NSTextField did change value in C#?


I created a Cocoa application in C# (using Xamarin.Mac) and I want to check if NSTextField did change the value. I couldn't find a lot of tutorials about this in C#, and the methods found for swift or overrides doesn't work for me. I tried this :

 public override void ObjectDidEndEditing(NSObject editor)

and

 public override void DidChangeValue(string forKey)

Solution

  • There are two ways to check if NSTextField did change the value.

    • One is using delegate the same as MacOS native method , however there is a liitle difference with navite code .

    As follow :

    textField.Delegate = new MyNSTextDelegate();
    

    Create a class inherite from NSTextFieldDelegate :

    class MyNSTextDelegate : NSTextFieldDelegate 
    {
       [Export("controlTextDidChange:")]
       public void Changed(NSNotification notification)
       {
           NSTextField textField = notification.Object as NSTextField;
           Console.WriteLine("Text Changed : " + textField.StringValue);
       }
    }
    
    • Another is using Event from C# Method .

    As follow:

    textField.Changed += TextValue_Changed;
    

    or

    textField.Changed += new EventHandler(TextValue_Changed);
    

    The implement of TextValue_Changed :

    private void TextValue_Changed(object sender, EventArgs e)
    {
        NSNotification notification = sender as NSNotification;
        NSTextField textField = notification.Object as NSTextField;
        Console.WriteLine("Text Changed : " + textField.StringValue);
    }