[英]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()
重載?
需要解決的兩個問題
ToString()
並引用 Key
或Value
的相應屬性。 否則這里是例子。 第一個是綁定到字典的列表框
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.