Datagrid.IsSelected绑定和滚动 [英] Datagrid.IsSelected Binding and scrolling

查看:110
本文介绍了Datagrid.IsSelected绑定和滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用MVVM,我将datagrid绑定到一些代码集合:

I uses MVVM and I bind datagrid to collection with some code:

<DataGrid ItemsSource="{Binding Entites}" AutoGenerateColumns="False" IsSynchronizedWithCurrentItem="True" 
                  SelectedItem="{Binding SelectedEntity}">

我使用style(RowStyle或ItemContainerStyle)绑定到IsSelectedProperty

And I aslo use binding to IsSelectedProperty using style (RowStyle or ItemContainerStyle)

<DataGrid.RowStyle>
        <Style>
              <Setter Property="DataGridRow.IsSelected" Value="{Binding IsSelectedProperty, Mode=TwoWay}" />                        
        </Style>
</DataGrid.RowStyle>

效果很好。但是如果我向下滚动datagrid,它会停止工作。

It works well. But if I scroll datagrid down and up, it stops working.

推荐答案

我遇到这个问题,原因是我的DataGrid是使用虚拟化 - 当您从屏幕上滚动所选的DataGridRow时,DataGridRow可视元素将被销毁,并创建一个新的DataGridRow,或者 - 如果DataGrid的 VirtualizingStackPanel.VirtualizationMode 属性是设置为回收 - 它被重新用于任何进入视口的行。

I encountered this problem, and the reason was my DataGrid was using virtualization - when you scroll a selected DataGridRow off the screen, the DataGridRow visual element is either destroyed, and a new one created, or - if the DataGrid's VirtualizingStackPanel.VirtualizationMode property is set to Recycling - it is reused for whatever row is entering the viewport.

当任何事件发生时,您的ViewModel(及其 IsSelectedProperty 属性集)和DataGridRow它的 IsSelected 属性集)被破坏。

When either event occurs, the binding between your ViewModel (with its IsSelectedProperty property set) and the DataGridRow (with its IsSelected property set) is broken.

要确认是这种情况,请尝试设置DataGrid的 EnableRowVirtualization 属性为false。

To confirm this is the case, try setting the DataGrid's EnableRowVirtualization property to false.

在我的情况下,我需要使用虚拟化所需的性能,最终使用< a href =http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx =noreferrer>附加行为:具体来说,单击一行将使用LeftClickCommand附加行为来调用ViewModel上的一个委托命令设置 IsSelectedProperty 。然后在DataGridRow的风格中使用 DataTrigger 绑定到 IsSelectedProperty 以突出显示该行。

In my case, I needed the performance required by using virtualization, and ended up implementing selectability using Attached Behaviors: specifically, a click on a row would use a LeftClickCommand attached behavior to invoke a delegate command on the ViewModel that sets IsSelectedProperty. I then used a DataTrigger bound to IsSelectedProperty in the DataGridRow's style to highlight the row.

此解决方案主要涉及滚动您自己的选择机制,但这是我发现获得行虚拟化和MVVM友好行选择的唯一方法。

This solution essentially involves rolling your own selection mechanism, but it was the only way I found to get both row virtualization and MVVM-friendly row selection.

这篇关于Datagrid.IsSelected绑定和滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆