Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting multiple records in DataGrid with Caliburn.Micro

I have a WPF application using Caliburn.Micro.

The DataGrid has an attribute SelectedItem="{Binding Path=SelectedUsageRecord}"

As you can see, SelectedItem is bound to SelectedUsageRecord property. But I need to be able to handle selecting multiple records. Is this possible to bind multiple records to a collection property? I don't see anything like "SelectedItems"... Thanks.

like image 241
David Shochet Avatar asked Dec 13 '22 02:12

David Shochet


2 Answers

Here's what I did after striking the same scenario as you. In short handle the selection change event directly and pull the selected rows from the event args. Assuming a source collection of "Rows" each one being a RowViewModel, and a collection for the "_selectedRows".

<DataGrid RowsSource="{Binding Rows}" x:Name="Rows"                  
          SelectionMode="Extended" SelectionUnit="FullRow">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <cal:ActionMessage MethodName="SelectedRowsChangeEvent">
                <cal:Parameter Value="$eventArgs" />
            </cal:ActionMessage>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</DataGrid>
public void SelectedRowsChangeEvent(SelectionChangedEventArgs e)
{
    foreach (var addedRow in e.AddedRows)
    {
        _selectedRows.Add(addedRow as RowViewModel);
    }

    foreach (var removedRow in e.RemovedRows)
    {
        _selectedRows.Remove(removedRow as RowViewModel);
    }
}
like image 125
Dave Avatar answered Dec 29 '22 11:12

Dave


I just wanted to post my solution. In Caliburn micro there is no need to set the source as long as you stay true to the naming convention.

Xaml

<DataGrid x:Name="Rows" SelectionMode="Extended" cal:Message.Attach="[Event SelectionChanged] = [Row_SelectionChanged($eventArgs)]">

C#

public List<MyObject> Rows { get; set; }

public MyObject SelectedRow { get; set; } //Will be set by Caliburn Micro. No need to use "SelectedItem={...}"

List<MyObject> _selectedObjects = new List<MyObject>();    

public void Row_SelectionChanged(SelectionChangedEventArgs obj)
{
  _selectedObjects.AddRange(obj.AddedItems.Cast<MyObject>());
  obj.RemovedItems.Cast<MyObject>().ToList().ForEach(w => _selectedObjects.Remove(w));
}
like image 33
Rahbek Avatar answered Dec 29 '22 10:12

Rahbek