簡體   English   中英

獲取WPF列表框中所選項目的文本

[英]Get the text of the selected item in a WPF listbox

我在WPF控件中有一個數據綁定列表框。 我想要的只是所選索引的文本。 如果我使用SelectedItem.ToString,我會得到密鑰和文本。 如果我使用SelectedValue.ToString我只得到密鑰。

一些論壇建議如下所示,但這似乎沒有用。

InputName nameInput = new InputName((ListBoxItem)LbContractors.SelectedItem.ToString()));

這就是我綁定控件的方式。 這搞砸了嗎?

LbContractors.ItemsSource = myDictionary;
LbContractors.SelectedValuePath = "Key";
LbContractors.DisplayMemberPath = "Value";

這應該可以解決問題。

(LbContractors.SelectedItem as ListBoxItem).Content.ToString();

UPDATE

或者嘗試這樣做。 轉換為Nullable KeyValuePair並獲取Value。

var kvp = (KeyValuePair<string, object>?) LbContractors.SelectedItem);
if(kvp != null && kvp.Value != null) {
    string selectedText = kvp.Value.ToString();
}

在一行中進行空檢查:)

string selectedText = ((KeyValuePair<string, object>?) LbContractors.SelectedItem)?.Value?.ToString();

為什么我不能像在winform中那樣簡單地抓取文本

如果對象被正確取消引用,就可以了....

我想要的只是所選索引的文本。

但是,根據您的示例,鍵值對結構的ToString()文本應該返回什么? 你有ToString()重載?

需要解決的兩個問題

  1. 你確定SelectedItem不是null嗎? 在訪問之前檢查該條件。
  2. 應該轉換為適當的結構(KVP),而不是盲目地調用ToString()引用 KeyValue的相應屬性。

否則這里是例子。 第一個是綁定到字典的列表框

myDictionary = new Dictionary<string, string>()
                {
                    {"Alpha", "The First Letter"},
                    {"Beta", "The Second Letter"},
                    {"Omega", "Omega Letter"},
                };

當用戶選擇每個項目時,鍵和值將顯示在列表框下方的文本框中:

在此輸入圖像描述

XAML

<ListBox  Name="lbDictionary"
          ItemsSource="{Binding myDictionary}"
          SelectedValuePath="Key"
          DisplayMemberPath="Value"/>

並在文本框中訪問它們( 為簡潔起見,我沒有顯示“Key”和“Value”的標簽

<TextBlock Text="{Binding SelectedItem.Key, ElementName=lbDictionary}"/>
...
<TextBlock Text="{Binding SelectedItem.Value, ElementName=lbDictionary}"/>

因此,訪問Key后面的代碼就是這樣, Value將是相同的:

if (lbDictionary.SelectedItem != null)
    MessageBox.Show(((KeyValuePair<string, string>) (lbDictionary.SelectedItem)).Key);
else
    MessageBox.Show("Select something");

為什么不使用LblContractors.Text; 如果這就是你要找的全部?

暫無
暫無

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

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