在MVVM中设置组合框的SelectedItem

时间:2014-05-10 03:41:16

标签: c# wpf mvvm combobox relaycommand

我有一个组合框,附带了各自命令的组合框的selectionchanged事件,并且在更改所选项目时(从下拉列表中)命令按预期触发,但是当我从代码中设置所选项目时没有。 / p>

这是我尝试过的一些代码

        Projects.Add(new Project { ProjectName = "Project 1" });
        Projects.Add(new Project { ProjectName = "Project 2" });
        Projects.Add(new Project { ProjectName = "Project 3" });
        Projects.Add(new Project { ProjectName = "Project 4" });  

        SelectedProject = Projects[0]; // I am expecting selection changed command execution here

   ICommand _projectSelectionChangedCommand;
   public ICommand ProjectSelectionChangedCommand
   {
     get
     {
       return _projectSelectionChangedCommand ?? (_projectSelectionChangedCommand = new RelayCommand(ProjectSelection));
     }
   }

 ObservableCollection<Project> _projects;
        public ObservableCollection<Project> Projects
        {
            get { return _projects; }
            set
            {
                _projects = value;


      NotifyPropertyChanged("Projects");
                }
            }

 public Project SelectedProject
        {
            get { return _selectedProject; }
            set
            {
                _selectedProject = value;
                NotifyPropertyChanged("SelectedProject");
            }
        }

我的xaml就是这个

   <ComboBox Grid.Row="1" Grid.Column="1" ItemsSource="{Binding Projects}" DisplayMemberPath="ProjectName" SelectedItem="{Binding SelectedProject}" >
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">
                <i:InvokeCommandAction Command="{Binding ProjectSelectionChangedCommand}"></i:InvokeCommandAction>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </ComboBox>

3 个答案:

答案 0 :(得分:1)

确保在SelectedItem Binding中使用Mode=TwoWay,否则无法保证所选项目会发生变化。

另外,请注意,尝试显式设置ComboBox可用的项目中不存在的值将导致它设置为null。尝试手动设置null会使行为更加奇怪,表明底层系统在集合之间使用空值与实际值。

答案 1 :(得分:1)

确保您的ComboBox为SelectedItem设置了TwoWay绑定,以及IsSynchronizedWithCurrentItem

   <ComboBox Grid.Row="1" Grid.Column="1" 
             ItemsSource="{Binding Projects}" 
             DisplayMemberPath="ProjectName"  
             SelectedItem="{Binding SelectedProject, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" 
             IsSynchronizedWithCurrentItem="True">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">
                <i:InvokeCommandAction Command="{Binding ProjectSelectionChangedCommand}"></i:InvokeCommandAction>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </ComboBox>

答案 2 :(得分:0)

我有一个模糊的回忆,在创建绑定之前必须将SelectedProject设置为有效的实例,如果它为null,则绑定会在从数据上下文到视图的方向上永久断开。