簡體   English   中英

如何使用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 [] 提供字符串數組會導致此錯誤:

錯誤CS1503:參數1:無法從'string []'轉換為'Foundation.NSObject []'(CS1503)

如何將項目添加到NSComboBox? 謝謝。

許多Cocoa(和iOS)控件都有DataSource屬性,這些屬性允許顯示,選擇,搜索等基於列/行的數據。

因此,創建一個NSComboBoxDataSource子類,並使其NSComboBoxDataSource接受一個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);

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM