WPF:为什么使用多个WindowsFormsHost时UI会变得缓慢?

本文关键字:UI 缓慢 WindowsFormsHost 为什么 WPF | 更新日期: 2023-09-27 18:04:40

我有一个数据绑定的TreeView与WindowsFormsHost在其项目的数据模板。TreeView中的项目越多,因此其中的WindowsFormsHost越多,UI变得越慢。

TreeView在TabItem中,它本身在TabControl中。当TabItem被选中时(即当我从另一个TabItem切换到带有TreeView的TabItem时),这种延迟是最明显的。

为了简化,我做了一个更简单的应用程序,用ListBox代替TreeView:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <TabControl>
        <TabItem Header="Tab 1">
            <StackPanel>
                <Button Content="Add 50 WindowsFormsHost controls" 
                        Click="Button_Click" />
                <ListBox Name="lst" Height="300">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <TextBlock Text="{Binding Path=Bar}" />
                                <WindowsFormsHost />
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </StackPanel>
        </TabItem>
        <TabItem Header="Tab 2" />
    </TabControl>
</Window>

在表单的代码中:

class Foo { public string Bar { get { return DateTime.Now.Ticks.ToString(); } } }
void Button_Click(object sender, RoutedEventArgs e)
{
    if (lst.ItemsSource == null)
        lst.ItemsSource = new ObservableCollection<Foo>();
     for (int j = 0; j < 50; j++)
        (lst.ItemsSource as IList<Foo>).Add(new Foo());
}

单击按钮后,滚动列表框的内容变得不那么流畅,并且在切换回选项卡1时存在延迟。

对于为什么会发生这种情况,以及是否有什么可以做的,有什么想法吗?

WPF:为什么使用多个WindowsFormsHost时UI会变得缓慢?

在WPF ListBox的项目中托管多个WindowsFormsHost,为什么不能在单个WindowsFormsHost中托管一个具有上述项目的WinForm ListBox ?这不仅会使滚动变得容易(由于完全在WinForms UI上下文中),而且还会使您的WPF应用程序内存效率更高(由于单个WindowsFormsHost)。

如果这不是你想要的,那么试着放松你的列表框的项目面板的虚拟化(默认情况下是VirtualizedStackPanel)。

让我知道这是否有帮助?