ItemsControl冻结元素生成的UI

时间:2017-03-30 10:38:19

标签: xaml uwp

我有一个ObservableCollection绑定到PivotItem中的ItemsControl。 我已经做到了这一点,ObservableCollection会以静默方式添加项目,只有在完成后才会触发通知。

生成项目时出现问题。我已经测试了codebehin并且所有内容都及时完成,但是在生成项目时UI会冻结。

这是这些ItemsControls的模板:

                <Style TargetType="ItemsControl">
                    <Style.Setters>
                        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                        <Setter Property="ItemTemplate" Value="{StaticResource TempCell}" />
                        <Setter Property="ItemsPanel">
                            <Setter.Value>
                                <ItemsPanelTemplate>
                                    <VariableSizedWrapGrid />
                                </ItemsPanelTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style.Setters>
                </Style>

问题似乎在于ItemTemplate,即使我向与之关联的DataTemplate添加一个空控件,它也会冻结UI。如果没有ItemTemplate则不行。

我添加了数千个控件,这些控件将一次显示,简单的ToggleButtons尺寸为25x25。

我在WPF中运行了非常相似的代码,然后将其转换为UWP并且没有冻结问题。 应用程序在生成过程后运行顺利。

根据要求提供附加代码:

    'Keep in mind that the item generation happens in a separate thread
    Await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Sub() List.Replace(Output))
    'That's why it has to replace the old collection with the new one silently
    'This code does not produce any bottleneck in WPF
    Public Sub Replace(list As IEnumerable(Of T))
        If list Is Nothing Then
            Throw New ArgumentNullException("list")
        End If

        _suppressNotification = True
        Clear()

        For Each item As T In list
            Add(item)
        Next

        _suppressNotification = False
        OnCollectionChanged(New Specialized.NotifyCollectionChangedEventArgs(Specialized.NotifyCollectionChangedAction.Reset))
    End Sub

    'Scratching the code above and just trying this, i get the same result, it freezes the UI as UWP elements are being generated, here they are added one by one, which should cause notificationchanged events to occur.
    Await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Sub() 
            List.Clear()
            For Each Item In Output
               List.Add(Item)
            Next
    End Sub)

    'These are the items generated, they refer to a global Random, changing it to a local Random, does not impact the freezing one way or the other.
    Parallel.For(0, CellsCount, Sub(i) Output.Add(New Cell With {.Color = Color.FromArgb(255, CByte(Random.Next(0, 256)), CByte(Random.Next(0, 256)), CByte(Random.Next(0, 256)))}))

0 个答案:

没有答案