gpt4 book ai didi

c# - 向 UI 添加内容时如何阻止 UI 被锁定

转载 作者:太空狗 更新时间:2023-10-30 01:18:18 25 4
gpt4 key购买 nike

我有 250 个可视对象,我需要将它们添加到 WrapPanel。当我这样做时,用户界面会锁定几秒钟,这不是我想要的。有办法阻止这种情况吗?

private void ButtonClick()
{
Foreach(Visual item in ListOfVisuals)
{
WrapPAnel.Children.Add(item);
}
}

据我所知,我无法创建新的 Task.Run() => ButtonClick 来执行此操作,因为任务无法访问 UI。

最佳答案

这里的实际问题是您添加的每个项目都会引发更改通知。

您需要将 WrapPAnel.Children 数据绑定(bind)到实现 AddRangeINotifyCollectionChanged 实例。目标应该是整个集合的属性更改事件只引发一次。

The obvious answer is, of course, just write a method which iterates over the input collection and calls Add for each. But this really isn’t the answer, because the question really isn’t about AddRange – the question is really about raising a single CollectionChanged event when adding multiple items

你是如何实现的?

    public void AddRange(IEnumerable<T> dataToAdd)

{

this.CheckReentrancy();



//

// We need the starting index later

//

int startingIndex = this.Count;



//

// Add the items directly to the inner collection



//

foreach (var data in dataToAdd)

{

this.Items.Add(data);

}



//

// Now raise the changed events

//

this.OnPropertyChanged("Count");

this.OnPropertyChanged("Item[]");



//

// We have to change our input of new items into an IList since that is what the

// event args require.

//

var changedItems = new List<T>(dataToAdd);

this.OnCollectionChanged(changedItems, startingIndex);

}

来源: http://blogs.msdn.com/b/nathannesbit/archive/2009/04/20/addrange-and-observablecollection.aspx

但是等等,你不能像那样绑定(bind) Wrappanel!您将需要使用 ItemsControl,其 ItemsPanelTemplate 设置为 WrapPanel。看这个例子http://tech.pro/tutorial/830/wpf-tutorial-using-an-itemspanel

<ItemsControl>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<Image Source="Images\Aquarium.jpg" Width="100"/>
<Image Source="Images\Ascent.jpg" Width="50"/>
<Image Source="Images\Autumn.jpg" Width="200"/>
<Image Source="Images\Crystal.jpg" Width="75"/>
<Image Source="Images\DaVinci.jpg" Width="125"/>
<Image Source="Images\Follow.jpg" Width="100"/>
<Image Source="Images\Friend.jpg" Width="50"/>
<Image Source="Images\Home.jpg" Width="150"/>
<Image Source="Images\Moon flower.jpg" Width="100"/>
</ItemsControl>

关于c# - 向 UI 添加内容时如何阻止 UI 被锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27860545/

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