如何使用Xamarin& amp;将项添加到macOS NSComboBox? C#?

时间:2017-12-12 09:20:07

标签: c# xamarin xamarin.mac visual-studio-mac nscombobox

我正在使用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" });

我希望使用Add函数将此列表添加到NSComboBox中:

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

添加功能支持添加 NSObject [] 。给字符串数组会导致此错误:

  

错误CS1503:参数1:无法从'string []'转换为'Foundation.NSObject []'(CS1503)

如何将项目添加到NSComboBox?感谢。

1 个答案:

答案 0 :(得分:2)

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

所以创建一个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);

enter image description here