簡體   English   中英

C#列表框項目標識

[英]C# listbox item identification

請記住,我對C#經驗不足。

我正在為列表框編碼一個刪除按鈕,並且刪除所選項目的基本功能起作用。

listBoxSum.Items.RemoveAt(listBoxSum.SelectedIndex);

我正在嘗試做一個IF語句,該語句使我可以從列表框中選擇一個項目,並使其標識其中的文本(最有可能是字符串)。

因為我對c#不太了解,所以這是我目前對if語句所擁有的(顯然第一行是錯誤的)。

if (listBoxSum.SelectedItem = "Tea")
        {
            totalCost = totalCost - teaCost;
            txtBox_Amount.Text = totalCost.ToString();
        }

我已經嘗試制作其他字符串來簡化這樣的語句( 以下不是if語句的主要代碼,上面的代碼是。這只是嘗試並擴展代碼以使其更易於理解的實驗我自己 ):

       string teaSelect = "Tea" + teaCost;
       string selection = (string) listBoxSum.SelectedItem;

       if (selection == teaSelect)
       {
            totalCost = totalCost - teaCost;
            txtBox_Amount.Text = totalCost.ToString();
       }

請幫助,我不知道我是否應該改變對此的想法,或者是否可以輕松地將其隱藏起來。 就我個人而言,我被這個小按鈕困住了大約2個小時,弄清楚我將如何使remove按鈕與計算一起工作。

您要檢查的是您當前正在查看的項目是否是ListBoxItem,如果是,則包含的內容是文本,並且此文本是否等於您想要的文本,以便標識正確的項目。

var content = (((x.SelectedItem as ListBoxItem)?.Content as string);
if (content != null && content == "MyDesiredText") {...}

這將是一個有效的解決方案,但不是一個很好的解決方案。 更好的方法是在創建列表框項目時記住它們

var desiredListBoxItem = new ListBoxItem(...)
x.AddChild(desiredListBoxItem);

然后,檢查對象引用是否匹配:

if (x.SelectedItem == desiredListBoxItem) {...}

如果您不更新包含“茶+成本”值的商品,則可能應該通過string.StartsWith進行標識,或者為它分配您所選擇的標識符。 這可以是整數,枚舉或具有預定義實例的其他具體類。

您可以通過使用WPF的Tag屬性並為Windows窗體創建一個簡單的類( WPF Tag屬性 )來做到這一點。

Windows窗體的一個簡單示例為:

enum FoodType
{
    Tea = 2
}
class FoodItem
{
    public string Text { get; set; }
    public FoodType FoodType { get; set; }

    public override string ToString()
    {
        return Text;
    }
}

添加項目時:

listBoxSum.Items.Add(new FoodItem
{
    FoodType = FoodType.Tea,
    Text = "Tea " + teaCost
});

當您過濾它們時:

if (listBoxSum.SelectedItem is FoodItem foodItem && foodItem.FoodType == FoodType.Tea)
{
    // Do work
}

對於WPF來說更容易:

enum FoodType
{
    Tea = 1
}

添加項目:

listBoxSum.Items.Add(new ListBoxItem
{
    Content = "Tea " + teaCost,
    Tag = FoodType.Tea
});

識別項目:

if (listBoxSum.SelectedItem is ListBoxItem foodItem && foodItem.Tag is FoodType foodType && foodType == FoodType.Tea)
{
    MessageBox.Show("hi");
}

因此,您在ListBox的項目稱為“茶”?如果是,則if語句應如下所示:

if(yourTextBox.Items[yourTextBox.SelectedIndex] == "Tea")
{
    //Your Code
}

暫無
暫無

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

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