组合框selectedvalue未更新
本文关键字:更新 selectedvalue 组合 | 更新日期: 2023-09-27 18:25:28
我正在进行一个WPF项目。我有一个组合框,我想在某个事件上更新它的Selected值。我的代码如下所示;
这是我的xaml代码
<ComboBox x:Name="cmbSeverity" Height="23"
Margin="10,157,0,0" VerticalAlignment="Top" Width="198"
HorizontalAlignment="Left" SelectedValuePath="Content">
<ComboBoxItem Content="Low"/>
<ComboBoxItem Content="Medium"/>
<ComboBoxItem Content="High"/>
</ComboBox>
这是我的CS代码
SomeEvent(){
cmbSeverity.SelectedValue = "High";
}
请指导我
您可以对SelectedItem
属性使用Databinding,并将其绑定到一个属性。例如:
在XAML中:
SelectedItem="{Binding MyProperty}"
在您的代码中:(最好是您的ViewModel)
public class MyViewModel : INofityPropertyChanged
{
private string _myProperty;
public string MyProperty
{
get { return _myProperty; }
set
{
_myProperty = value;
NotifyPropertyChanged("MyProperty");
}
}
private void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
public event PropertyChangedEventHandler PropertyChanged;
}
您已将ItemsSource声明为ComboBoxItems的集合,并试图将所选值设置为字符串,但这将不起作用,因为ItemsSource集合类型和所选值类型应相同。
因此,将您的声明更改为此,它将工作(使用字符串对象而不是comboBoxItems):
<ComboBox x:Name="cmbSeverity" Height="23"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Margin="10,157,0,0" VerticalAlignment="Top" Width="198"
HorizontalAlignment="Left">
<sys:String>Low</sys:String>
<sys:String>Medium</sys:String>
<sys:String>High</sys:String>
</ComboBox>