我有这样的代码:
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type local:MyViewModel}">
<!-- xaml is typed here directly -->
<Border>
...
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
而且 DataTemplate 中的 xaml 很大(超过 200 行)。
我想将 DataTemplate 中的 xaml 移动到单独的 UserControl 中,以便于编辑和维护。我接下来要做的是:
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type local:MyViewModel}">
<!-- xaml is moved to separate UserControl -->
<local:MyViewModelUserControl />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我遇到的问题是渲染/处理第二个代码(使用 UserControl)比第一个代码花费大约 2 倍的时间。任何想法如何处理它?</p>
注意:我移动的不是 ListBox,而是 DataTemplate 内的 xaml。原因不是为了重用这段代码,而是为了最小化放置ListBox的主文件。另一件事是我在 ListBox 中有几个 DataTemplates(用于几个 ViewModels)并且 xaml 非常大。这就是为什么我想将此 xaml(位于 DataTemplate 内)移动到单独的控件。
最佳答案
我知道这是一个老问题,但我最近也遇到了这个问题。在 WPF 中创建用户控件的开销很大,这似乎来自将代码隐藏类文件连接到 XAML。如果您只想将 XAML 移动到另一个位置,只需在另一个文件的 ResourceDictionary
中定义您的 DataTemplate
,并将其作为 StaticResource加载
。这将提供一些优势:
(1) 能够对元素使用 x:Name
,这在内联 DataTemplate
中是不允许的。
(2) 性能。具有直接 XAML 的 DataTemplate
比 DataTemplate
中的 UserControl
快几个数量级。
(3)清洁度。您可以在任何您喜欢的地方定义 DataTemplate
(同一文件中的资源字典,您正在使用它的地方附近,不同的文件等)并将其称为 StaticResource
.
关于wpf - 为什么在 DataTemplate 中使用 UserControl 比直接 xaml 慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38610377/