WPF ComboBox 和所选项目的问题

Jim*_*Del 3 c# wpf

我有最糟糕的时间让 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>
Run Code Online (Sandbox Code Playgroud)

后面有 C# 代码...

private void comboBox_SelectionChanged(object sender, selectionChangedEventArgs e)
{
    string val = comboBox.SelectedValue.ToString();
}
Run Code Online (Sandbox Code Playgroud)

val 的值将是...

System.Windows.Controls.ComboBoxItem:组合框项目 #2

“System.Windows.Controls.ComboBoxItem:”从何而来,我该如何摆脱它?

谢谢

Cha*_*ger 8

SelectedValue在这种情况下将返回一个ComboBoxItem. 你所看到的是调用它的结果ToString

如果您只想要that的内容ComboBoxItem,则需要访问它:

var item = (ComboBoxItem)comboBox.SelectedValue;
var content = (string)item.Content;
Run Code Online (Sandbox Code Playgroud)

或者,设置SelectedValuePath="Content"(在 XAML 中)然后SelectedValue将简单地返回内容字符串。