在我的 xaml 代码中,在该Window.Resources
部分内,我定义了一个带有x:key
.
<Window.Resources>
<DataTemplate x:key>
...
</DataTemplate>
</Window.Resources>
我有一个列表框,我必须在 .xaml.cs 代码中将此数据模板分配给该列表框。这是怎么做到的?
使用 ItemTemplate 在 XAML 中以声明方式将数据模板分配给列表中的每个项目
<ListBox ItemTemplate="{StaticResource YourResourceKey}">
假设您的 DataTemplate 被称为 YourResourceKey
<DataTemplate x:Key="YourResourceKey">
在窗口的代码隐藏中,您可以这样做:
myListBox.ItemTemplate = (DataTemplate)Resources["resourceKey"];
除非您有理由使用代码隐藏,否则我会坚持使用 XAML 并使用 @Charleh 的方法。