Problems with checkbox in wpf mvvm

I have a problem when I use CheckBoxin mine GridViewusing WPF and MVVM.

 <GridViewColumn.CellTemplate>
                  <DataTemplate>
                     <CheckBox IsChecked="{Binding IsSelected}"/>
                   </DataTemplate>
  </GridViewColumn.CellTemplate>

My viewmodel

 public bool IsSelected
    {
        get
        {
            return _isSelected;
        }
        set
        {
            if (_isSelected == value)
            {
                return;
            }
            _isSelected = value;
            OnPropertyChanged("IsSelected");
        }
    }

How can I select the data in the selected row, i.e. is the value of CheckBoxthis string true?

+4
source share
1 answer

You will need to configure IEnumerable<bool>/ IEnumerable<SomeClass>, which contains information IsCheckedfor each of your CheckBoxes. Sort of

public class CheckedItem
{
    public CheckedItem() { }

    public CheckedItem(string text, bool isChecked) : this()
    {
        this._text = text;
        this._isChecked = isChecked;
    }

    private string _text;
    public String Text;
    {
        get { return _text; }
        set
        {
            if (_text == value)
                return;
            _text = value;
            OnPropertyChanged("IsSelected");
        }
    }

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

private ObservableCollection<CheckedItem> checkItemCollection = 
    new ObservableCollection<CheckedItem>();
public ObservableCollection<CheckedItem> CheckItemCollection
{
    get { return checkItemCollection; }
    set
    {
        if (checkItemCollection == value)
            return;
        checkItemCollection = value;
        OnPropertyChanged("CheckItemCollection");
    }
}

in xaml you can bind GridViewto this with

<GridView ItemsSource="{Binding Path=CheckedItemCollection, 
                                Mode=TwoWay, 
                                UpdateSourceTrigger=PropertyChanged, 
                                IsAsync=True}" 
    <GridView.Columns>
        <GridViewColumn.CellTemplate>
            <DataTemplate>
                <CheckBox Content="{Binding Text}" 
                          IsChecked="{Binding IsSelected, 
                                              Mode=TwoWay, 
                                              UpdateSourceTrigger=PropertyChanged, 
                                              IsAsync=True}"/>
            </DataTemplate>
        </GridViewColumn.CellTemplate>
    </GridView.Columns>
</GridView>

This was done without an IDE, so you may have to configure it to make it work.

Hope this helps.

+3
source

Source: https://habr.com/ru/post/1523674/


All Articles