Combobox selectedvalue未更新

时间:2014-10-03 06:51:13

标签: c# wpf xaml combobox wpf-controls

我正在开发一个WPF项目。我有一个ComboBox,我想在某个事件上更新它的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"; 
}

请指导我

2 个答案:

答案 0 :(得分:2)

您可以在SelectedItem属性上使用数据绑定,并将其绑定到属性。如:

在您的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;
}

答案 1 :(得分:1)

您已将ItemsSource声明为ComboBoxItems的集合,并尝试将所选值设置为字符串,但这不起作用,因为 ItemsSource集合类型和所选值类型应相同

所以,将你的声明改为this并且它将起作用(使用字符串对象而不是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>
相关问题