开发者

WPF: Why does the UI become sluggish with multiple WindowsFormsHost?

开发者 https://www.devze.com 2023-03-26 07:00 出处:网络
I have a data-bound TreeView with a WindowsFormsHost in the data template of its items. The more items in the TreeView, and so the more WindowsFormsHost in it, the slower the UI becomes.

I have a data-bound TreeView with a WindowsFormsHost in the data template of its items. The more items in the TreeView, and so the more WindowsFormsHost in it, the slower the UI becomes.

The TreeView is in a TabItem, itself in a TabControl. The sluggishness is most obvious whenever the TabItem is selected (ie when I switch from another TabItem to the TabItem with the TreeView).

To simplify, I made a simpler app with a ListBox instead of a 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>

With this in the form's code:

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());
}

After clicking the button, scrolling the ListBox's content becomes less fluid, and there is a delay when switching back to Tab 1.

Any ideas on why this is happening, and on if there is anything to do about it?


Instead of hosting multiple WindowsFormsHost in a WPF ListBox's items, why cant you host one WinForm ListBox having above items in a single WindowsFormsHost? This would not only make the scrolling easy (due to entirely in WinForms UI context) but also make your WPF app memory efficient (due to single WindowsFormsHost).

If this is not what you are for, then try to loose the Virtualisation of your ListBox's Items Panel (which by default is a VirtualizedStackPanel).

Let me know if this helps?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号