如何使用 Xamarin 和 C# 将项目添加到 macOS NSComboBox?

How Can I Add Item to macOS NSComboBox with Xamarin & C#?

我正在使用 Xamarin 和 C# 开发 macOS 应用程序。我在故事板中有一个 NSComboBox。它有一个插座,所以我可以成功访问它。

我有一个数据上下文,它填充在这样的列表中:

public static List<string> bloomTypes_EN = new List<string>(new string[] {
        "Cognitive Memory",
        "Cognitive Understanding",
        "Cognitive Practice",
        "Cognitive Analysis",
        "Cognitive Evaluation",
        "Cognitive Generation",
        "Affective Reception",
        "Affective Behavior",
        "Affective Valuing",
        "Affective Organization",
        "Affective Character Making",
        "Psychomotor Perception",
        "Psychomotor Organization",
        "Psychomotor Guided Behavior",
        "Psychomotor Mechanization",
        "Psychomotor Complex Behavior",
        "Psychomotor Harmony",
        "Psychomotor Generation" });

我想使用添加功能将此列表添加到 NSComboBox 中:

 if(EarnArea_ComboBox.Count !=  0) // If not empty.
        {
            EarnArea_ComboBox.RemoveAll(); // delete all items.
        }
        else // Empty.
        {
            EarnArea_ComboBox.Add(values.ToArray());
        }

添加函数支持添加NSObject[]。提供字符串数组会导致此错误:

Error CS1503: Argument 1: cannot convert from 'string[]' to 'Foundation.NSObject[]' (CS1503)

如何向 NSComboBox 添加项目?谢谢

许多 Cocoa(和 iOS)控件具有 DataSource 属性,允许显示、选择、搜索等基于 column/row 的数据...

因此创建一个 NSComboBoxDataSource 子类并让它在其 .actor 中接受一个 List<string>:

public class BloomTypesDataSource : NSComboBoxDataSource
{
    readonly List<string> source;

    public BloomTypesDataSource(List<string> source)
    {
        this.source = source;
    }

    public override string CompletedString(NSComboBox comboBox, string uncompletedString)
    {
        return source.Find(n => n.StartsWith(uncompletedString, StringComparison.InvariantCultureIgnoreCase));
    }

    public override nint IndexOfItem(NSComboBox comboBox, string value)
    {
        return source.FindIndex(n => n.Equals(value, StringComparison.InvariantCultureIgnoreCase));
    }

    public override nint ItemCount(NSComboBox comboBox)
    {
        return source.Count;
    }

    public override NSObject ObjectValueForItem(NSComboBox comboBox, nint index)
    {
        return NSObject.FromObject(source[(int)index]);
    }
}

现在您可以将此应用到您的 NSComboBox:

EarnArea_ComboBox.UsesDataSource = true;
EarnArea_ComboBox.DataSource = new BloomTypesDataSource(bloomTypes_EN);