开发者

WPF DataGrid SelectedItems - keeping multiple selected while left clicking

is there a way to mimic the behavior of ctrl+click which keeps previously selected rows selected and just adds more selected items?

by default, when clicking on each row, all previously selected rows g开发者_JS百科et de-selected.

one way to achieve this, would be to override SelectionChanged event, and re-select removed rows.

void TestGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) {
    foreach (var i in e.RemovedItems)
        TestGrid.SelectedItems.Add(i);

}

This is not ideal however, because in some situations i would want to de-select rows (such as when clicking a toggle button in one of the columns).


This is not pretty, but it works if you can live with selecting multiple rows by dragging not working.

private void dataGrid_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    var dep = (DependencyObject)e.OriginalSource;

    // iteratively traverse the visual tree
    while ((dep != null) &&
        !(dep is DataGridRow))
    {
        dep = VisualTreeHelper.GetParent(dep);
    }

    if (dep == null)
        return;

    if (dep is DataGridRow)
    {
        var row = dep as DataGridRow;
        row.IsSelected = !row.IsSelected;
        e.Handled = true;
    }
}


Set the SelectionMode to DataGridSelectionMode.Extended


here's a solution that worked for me.

i removed all properties that set details visiblity (to keep everything at default)

than added the following style

<Style x:Key="VisibilityStyle" TargetType="{x:Type DataGridRow}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=Visible}" Value="False">
            <Setter Property="DetailsVisibility" Value="Collapsed" />
        </DataTrigger>
        <DataTrigger Binding="{Binding Path=Visible}" Value="True">
            <Setter Property="DetailsVisibility" Value="Visible" />
        </DataTrigger>
    </Style.Triggers>
</Style>

assigned this resource to RowStyle

in my underlying data object, i added Visible property, and Implemented INotifyPropertyChanged interface.

now whenever i want to show/hide details, i simply manipulate the Visible property on my underlying object. this can happen from column button handler, to anywhere else in my code. works great

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜