如何从下面的示例中获取所选值(例如Option1)string.我在Google上尝试过大量的建议,但无法获得字符串.
XAML:
<ComboBox x:Name="selectOption" Text="Select Option"
SelectionChanged="selectOption_SelectionChanged"
SelectedValue="{Binding VMselectedOption, Mode=TwoWay}" >
<ComboBoxItem Name="cbb1">Option1</ComboBoxItem>
<ComboBoxItem Name="cbb2">Option2</ComboBoxItem>
<ComboBoxItem Name="cbb3">Option3</ComboBoxItem>
</ComboBox>
Run Code Online (Sandbox Code Playgroud)
代码隐藏:
private void selectOption_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedValue = selectOption.SelectedValue;
}
//elsewhere in code
var test = viewModel.VMselectedOption;
Run Code Online (Sandbox Code Playgroud)
selectedValue和test都返回字符串" System.Windows.Controls.ComboBoxItem:Option1 "而不是" Option1 "
这应该是非常简单但我不能让这个工作或看到什么是错的?
Sup*_*aya 21
您应该设置SelectedValuePath ="Content".
<ComboBox x:Name="selectOption" Text="Select Option"
SelectionChanged="selectOption_SelectionChanged"
SelectedValue="{Binding VMselectedOption, Mode=TwoWay}"
SelectedValuePath="Content">
<ComboBoxItem Name="cbb1">Option1</ComboBoxItem>
<ComboBoxItem Name="cbb2">Option2</ComboBoxItem>
<ComboBoxItem Name="cbb3">Option3</ComboBoxItem>
</ComboBox>
Run Code Online (Sandbox Code Playgroud)
Vla*_*lad 13
您不应手动插入组合框项目.使用它们设置它们ItemsSource.
基本上你应该创建一个选项列表(或代表选项的对象)并将它们设置为ItemsSource,这样你SelectedItem将完全是选择的选项,而不是自动创建的包装ComboboxItem.
string Value="";
if(myComboBox.SelectedIndex>=0)
Value=((ComboBoxItem)myComboBox.SelectedItem).Content.ToString();
Run Code Online (Sandbox Code Playgroud)
更新代码以获取comboboxItem的内容.
var selectedValue = ((ComboBoxItem)selectOption.SelectedItem).Content.ToString();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48179 次 |
| 最近记录: |