[英]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.