我刚开始使用WPF表单而不是Windows Forms表单.在Windows窗体表单中,我可以这样做:
ComboBox.SelectedValue.toString();
Run Code Online (Sandbox Code Playgroud)
这样可以正常工作.
我如何在WPF中执行此操作?它似乎没有选择权.
小智 81
嗯..我找到了一个更简单的解决方案.
String s = comboBox1.Text;
Run Code Online (Sandbox Code Playgroud)
这样我将所选值作为字符串.
Boa*_*rdy 75
与旧的WF表格相比,我已经想出了一些奇怪的做法:
ComboBoxItem typeItem = (ComboBoxItem)cboType.SelectedItem;
string value = typeItem.Content.ToString();
Run Code Online (Sandbox Code Playgroud)
The*_*est 11
确保您已在XAML文件中设置ComboBox的名称:
<ComboBox Height="23" Name="comboBox" />
Run Code Online (Sandbox Code Playgroud)
在您的代码中,您可以使用SelectedItem
属性访问所选项目:
MessageBox.Show(comboBox.SelectedItem.ToString());
Run Code Online (Sandbox Code Playgroud)
Kun*_*osh 10
我的XAML如下:
<ComboBox Grid.Row="2" Grid.Column="1" Height="25" Width="200" SelectedIndex="0" Name="cmbDeviceDefinitionId">
<ComboBoxItem Content="United States" Name="US"></ComboBoxItem>
<ComboBoxItem Content="European Union" Name="EU"></ComboBoxItem>
<ComboBoxItem Content="Asia Pacific" Name="AP"></ComboBoxItem>
</ComboBox>
Run Code Online (Sandbox Code Playgroud)
内容显示为文本和WPF组合框的名称.要获取所选项目的名称,我必须遵循以下代码行:
ComboBoxItem ComboItem = (ComboBoxItem)cmbDeviceDefinitionId.SelectedItem;
string name = ComboItem.Name;
Run Code Online (Sandbox Code Playgroud)
要获取WPF组合框的选定文本:
string name = cmbDeviceDefinitionId.SelectionBoxItem.ToString();
Run Code Online (Sandbox Code Playgroud)
小智 7
作为 ComboBoxSelectionChanged
事件处理程序中的变体:
private void ComboBoxName_SelectionChanged(object send ...
{
string s = ComboBoxName.Items.GetItemAt(ComboBoxName.SelectedIndex).ToString();
}
Run Code Online (Sandbox Code Playgroud)
这取决于你绑定到ComboBox的内容.如果您已绑定叫MyObject的对象,并且有,比方说,一个属性称为名称请执行以下操作:
MyObject mo = myListBox.SelectedItem as MyObject;
return mo.Name;
Run Code Online (Sandbox Code Playgroud)
这些怎么样:
string yourstringname = (yourComboBox.SelectedItem as ComboBoxItem).Content.ToString();
Run Code Online (Sandbox Code Playgroud)