WPF - VirtualizingStackPanel 为 ListView 创建项目时需要一个事件
有什么方法可以判断 ListView 的容器何时完成?
详细解释我到目前为止所做的事情
我有一个 ListView 控件,该控件的其中一列中有一个 DataTemplate,其中包含一个 CheckBox 控件。我已经弄清楚如何动态访问 CheckBox使用 ListView 绑定到的对象。
ListViewItem lItem = (ListViewItem)ListView.ItemContainerGenerator.ContainerFromItem(trackToHandle);
CheckBox checkBoxToHandle = FindChild<CheckBox>(lItem, "CheckBox");
问题是,每当我滚动太远或对列进行排序时,复选框都会“重置”(变为未选中状态)。 我发现这是因为 VirtualizingStackPanel 只为那些可见(或几乎可见)的 ListViewItems 吐出容器。 由于 CheckBox 位于 XAML 中定义的 DataTemplate 内部,因此每次它离开视图或对列表进行排序时,它都会被丢弃。
我通过创建一个单独的复选框列表并使用实际的复选框“单击”事件来更改列表中相应复选框的状态来解决这个问题。然后制作了一个小方法来更改所有可见复选框的状态用户滚动...结果它看起来应该是首先的。
除非我对列进行排序。 我尝试让它在对列进行排序后立即重新执行复选框(像以前一样),但它不起作用。 我最好的猜测是,在我排序后它不会立即创建容器。
有什么方法可以告诉 ListView 容器何时完成创建?
Is there any way to tell when the containers are finished being made for a ListView?
A detailed explanation of what I've done so far
I have a ListView control that has a DataTemplate in one of its columns that contains a CheckBox Control.. I've figured out how to access the CheckBox dynamically using the object that the ListView is bound to.
ListViewItem lItem = (ListViewItem)ListView.ItemContainerGenerator.ContainerFromItem(trackToHandle);
CheckBox checkBoxToHandle = FindChild<CheckBox>(lItem, "CheckBox");
The problem is that the CheckBoxes "reset" (become unchecked) whenever I scroll too far or whenever I sort the columns.
I figured out this was because the VirtualizingStackPanel was only spitting out containers for those ListViewItems that were visible (or almost visible)..
And because the CheckBox is inside a DataTemplate that is defined in the XAML it gets thrown away everytime it goes out of view or when the list is sorted.
I got around this by creating a separate list of CheckBoxes and using the actual CheckBoxes "click" event to change the state of the corresponding CheckBox in my list.. then made a little method to go change the state of all the visible CheckBoxes whenever the user scrolls... as a result it appears like it should have in the first place.
Except when I sort the columns.
I tried making it re-do the CheckBoxes (like before) right after it'd sorted a column but it didn't work.
My best guess is that it doesn't immediately make the containers after I sort..
Is there any way to tell when the containers are finished being made for a ListView?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果将复选框 IsChecked 属性绑定到数据上下文上的布尔属性,则不会出现此问题。
VirtualizingStackPanel 的全部目的是通过除非需要时不创建 ListItem 来减少内存使用量。
实际上,您需要将复选框的数据侧移离控件。
If you bind your checkboxes IsChecked property to a boolean property on your data context, then you will not have this issue.
The whole purpose of the VirtualizingStackPanel is reduce memory usage by not creating ListItem's unless needed.
In effect, you need to move the data side of the checkbox away from the control.