简体   繁体   中英

MVVM WPF ComboBox with CheckBox

I've tried to search for this for quite some time and haven't found results that help. (perhaps my google-foo needs work?) I'm also fairly new to WPF MVVM, so there is a lot I'm still learning.

My Question is actually in two parts... Firstly, I have a Combobox that has Checkboxes within them within a View. Code:

 <ComboBox Grid.Column="0"
                      Grid.ColumnSpan="5"
                      Margin="15,0,0,0"
          ItemsSource="{Binding StaffNames}" 
                      SelectedValue="{Binding SelectedStaffNames}"
          Grid.Row="4">
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <CheckBox Content="{Binding Path=FullName}"
                                  VerticalAlignment="Center"
                                  IsChecked="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ComboBoxItem}},     Path=IsSelected,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"
                                  Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window},
                            Path=DataContext.CheckBoxSelected}"
                                  Margin="3">  
                        </CheckBox>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>

Everytime I check a checkbox, it seems that the checkboxes get automatically unchecked.

My ViewModel code is as follows.

private bool _isSelected;
        public bool IsSelected
        {
            get
            {
                return _isSelected;
            }
            set
            {
                _isSelected = value;
                RaisePropertyChanged("IsSelected");
            }
        }

What is wrong here?

My second question is: Once the above is resolved, I need to append all checked names (staff names in this case) to a list and pass the values back to a separate view/view model.

I'm at a complete loss for how to accomplish this. Any help or suggestions would be greatly appreciated.

Thanks :)

2 things that could be going wrong

  1. Are you trying to set the check box value in your command - "DataContext.CheckBoxSelected"? Since you already have a binding, this could be resetting the value.

  2. Clicking the checkbox does not update selected item in combo box but only updates the checkbox.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM