【问题标题】:Combobox selectedvalue is not updating组合框选定值未更新
【发布时间】:2014-10-03 06:51:12
【问题描述】:

我正在开发一个 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"; 
}

请指导我

【问题讨论】:

    标签: c# wpf xaml combobox wpf-controls


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您已将 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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-06
        • 1970-01-01
        • 2020-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多