2014-10-03 80 views
0

我正在开发一个WPF项目。我有一个组合框,我想更新某个事件的选定值。我的守则如下:Combobox selectedvalue没有更新

这里是我的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"; 
} 

请指引我

回答

1

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

在您的XAML:

SelectedItem="{Binding MyProperty}" 

在您的代码:(最好是你的视图模型)

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

您已经声明的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>