简体   繁体   中英

How to bind two things to IsChecked property of checkbox?

Ok, so I have a datagrid with a checkbox in a DataGridTemplateColumn since I would like to do a single-click check. I also have a "select all" checkbox at the top. (I disabled the header because I wanted to make a custom one). My datagrid is programmatically populated. and I'm using the mahApps nuget package (if that means anything).

What I want to do is bind the "Select All" status to the IsChecked property on my populated checkboxes but also be able to click the row to check the checkbox. But to be able to do that, I need to add: IsChecked="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow}, Path=IsSelected, Mode=OneWay}" .

I have both of them, and they both work, but I can only seem to use one at a time. How would I go about doing both? Please let me know if you need more info

Edit: I would also need multi-selection!

This is psuedo code:

To make each rows checkbox clickable independently - the ViewModel for row should have bool IsChecked get set property. For Top level "Select All" checkbox - you will need a top level bool? SelectAll get set property too - getter will be something like --

Lets says collection bound to GridView is

List<RowViewModel>RowViewModelCollection;

Then each RowViewModel object will have:

private bool _IsSelected = null;
public bool IsSelected
{
    get => _IsSelected;
    set
    {
        _IsSelected  = value;
        // NotifyProperty Change for this property
        // Notify Property Change for TopLevel SelectAll property
    }
}

Your Top level SelectAll should look like:

public bool? SelectAll
{
    get
    {
        if(RowViewModelCollection.All(r=>r.IsSelected == true))
            return true;
        else if(RowViewModelCollection.All(r=>r.IsSelected == false))
            return false;
        else
            return null;
    }
    set
    {
       foreach(var row in RowViewModelCollection)
       {
          row.IsSelected = value;
       }

       // Notify Property Changed for This property
    }
}

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