[英]Trouble with WPF ComboBox and selected item
我最迫切的時間讓ComboBox正常工作。 下面的XAML ...
<ComboBox x:Name="comboBox" SelectionChanged="comboBox_SelectionChanged">
<ComboBoxItem>ComboBox Item #1</ComboBoxItem>
<ComboBoxItem>ComboBox Item #2</ComboBoxItem>
<ComboBoxItem>ComboBox Item #3</ComboBoxItem>
</ComboBox>
后面有C#代碼...
private void comboBox_SelectionChanged(object sender, selectionChangedEventArgs e)
{
string val = comboBox.SelectedValue.ToString();
}
val的值將是...
System.Windows.Controls.ComboBoxItem:ComboBox項目#2
“ System.Windows.Controls.ComboBoxItem:”從哪里來,我如何擺脫它?
謝謝
在這種情況下, SelectedValue
將返回ComboBoxItem
。 您所看到的是對此調用ToString
的結果。
如果只需要該ComboBoxItem
的內容 ,則需要訪問它:
var item = (ComboBoxItem)comboBox.SelectedValue;
var content = (string)item.Content;
或者,在XAML中設置SelectedValuePath="Content"
,然后SelectedValue
將僅返回內容字符串。
因此組合框具有類型組合框項目的集合。 因此,當您選擇一個項目時,選定的項目依賴項屬性將成為組合框項目類型的特定實例。 在組合框項目上調用ToString()
方法,導致輸出:
System.Windows.Controls.ComboBoxItem:ComboBox項目#2
若要獲取組合框項目的值,您可以嘗試調用項目的Content
屬性。 請記住,盡管內容可以是任何東西。 一種常見的做法是將組合框綁定到集合(通常是ObservableCollection<T>
),並且所選項目的類型為T
從那里可以獲取對象的特定屬性。 一個示例類似於以下內容
C#
public class MyType
{
public int ID {get; set;}
public string Text {get; set;}
}
//CodeBehind
public class CodeBehindClass
{
public ObservableCollection<MyType> MyCollection {get; set;} = new ObservableCollection();
public MyType SelectedItem {get; set;}
//Populate collection
MyComboBox.ItemsSource = MyCollection;
private void MyComboBox_SelectionChanged(object sender, selectionChangedEventArgs e)
{
SelectedItem = (MyType)MyComboBox.SelectedValue;
//display string with SelectedItem.Text;
}
}
XAML
<ComboBox x:Name="MyComboBox" SelectionChanged="MyComboBox_SelectionChanged" />
System.Windows.Controls.ComboBoxItem:ComboBox項目#2
來自SelectedValue
因為它返回整個對象而不僅僅是字符串。
您可以嘗試GetItemText
而我修改了您的代碼以適應您的要求:
private void comboBox_SelectionChanged(object sender, selectionChangedEventArgs e)
{
this.ComboBox.GetItemText(this.Combobox.SelectedItem);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.