gpt4 book ai didi

c# - 复选框绑定(bind)慢

转载 作者:太空宇宙 更新时间:2023-11-03 16:01:24 24 4
gpt4 key购买 nike

我在这里有点为难(没有双关语意);我有大量 View 模型(500 多个),它们使用 ItemsControlWrapPanel 作为 ItemsPanelTemplate 显示。这些 View 模型中的每一个都公开了一个 Boolean?,其值绑定(bind)到用户界面上 CheckBoxIsChecked 属性。

问题是...每当我尝试一次更新所有复选框时,速度都非常慢。更新包含 500 个项目的列表几乎需要 10 秒。如果我在单独的线程中运行更新代码,我几乎可以看到复选框一个一个地更新。

谁能告诉我为什么这个过程如此缓慢以及我该如何改进它?

我认为 WrapPanel 的非虚拟化特性可能是有罪的一方。但是,当我绑定(bind)到 IsEnabled 属性而不是 IsChecked 时,我看到了一个有趣的结果;也就是说,将 IsEnabled 的值更改为 true 的速度如预期的那样慢,但更改为 false 会立即发生。这让我怀疑复选框动画有问题,因为据我所知,禁用复选框时没有动画,但启用时有。分析显示绝大部分时间花在 PropertyChangedEventManager.OnPropertyChanged() 方法上。

下面的示例代码,不幸的是我被迫使用 .NET 3.5:

XAML:

<ItemsControl ItemsSource="{Binding ChildItems}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type SampleViewModel}">
<CheckBox IsThreeState="True" IsChecked="{Binding Path=IncludeInPrinting, Mode=OneWay}" />
</DataTemplate>
</ItemsControl.Resources>
</ItemsControl>

View 模型:

public class SampleViewModel : INotifyPropertyChanged
{
private Boolean? _includeInPrinting;
public Boolean? IncludeInPrinting
{
get
{
return _includeInPrinting;
}
set
{
if (_includeInPrinting != value)
{
_includeInPrinting = value;
RaisePropertyChanged(() => IncludeInPrinting);
}
}
}
}

慢代码:

foreach (SampleViewModel model in ChildItems)
{
model.IncludeInPrinting = false;
}

编辑:值得一提的是,每当我选中所有或取消选中所有复选框时,我也会看到内存使用量激增。 ~10MB

编辑:下面的性能分析似乎证实动画绝对是问题所在。 Performance Analysis Hot Path

最佳答案

我会查看以下在 CodePlex 上开源的控件..

http://virtualwrappanel.codeplex.com/ (注意:我与 Virtualizing Wrap Panel 没有任何关系)

由于您正在使用大量的 View 模型,这将大大提高您的性能。

关于c# - 复选框绑定(bind)慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21165004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com