我在其项目的数据模板中有一个带有 WindowsFormsHost 的数据绑定 TreeView。TreeView 中的项目越多,因此其中的 WindowsFormsHost 越多,UI 变得越慢。
TreeView 位于 TabItem 中,它本身位于 TabControl 中。选择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());
}
单击按钮后,ListBox 的内容滚动变得不流畅,切换回 Tab 1 时会有延迟。
关于为什么会发生这种情况以及是否有什么可做的任何想法?