我有一个列表框,我必须在其中添加大约 20 个静态自定义项目。所有项目都基于相同的模板(类似的东西):
<Border>
<StackPanel Orientation="Horizontal">
<Image Source="" Height="30" />
<TextBlock Text="" VerticalAlignment="Center" />
</StackPanel>
</Border>
我不想在 ListBox.Items 中重复 20 次,我希望有某种 UserControl,我可以在其中执行如下操作,我可以在其中设置一些自定义属性:
<ListBox>
<ListBox.Items>
<MyListBoxTemplate x:Name="Item1" ItemText="Item #1" ItemImageSource="/Image1.jpg" />
<MyListBoxTemplate x:Name="Item2" ItemText="Item #2" ItemImageSource="/Image2.jpg" />
...
</ListBox.Items>
</ListBox>
但我不想为此创建一个用户控件!有没有一种简单的方法可以将该模板放入 Window.Resources 中?
谢谢
最佳答案
如果您仅将其用于特定列表框,则只需分配 ItemTemplate属性(property)。这需要与其他地方的资源中定义的自定义对象集合结合使用。这将使您免于创建自定义 UserControl,但无论如何您都需要一个可以在 XAML 中定义的对象以及它们的列表。说实话,创建 UserControl 相对来说比较轻松,而且可能更容易,但不这样做也是可能的。
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate TargetType="CustomObjectType">
<Border>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding ImageSource}" Height="30" />
<TextBlock Text="{Binding TextContent}" VerticalAlignment="Center" />
</StackPanel>
</Border>
<DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
编辑:如果您要在多个地方使用它,请将 DataTemplate
放入您的应用程序资源中并为其提供一个键,然后分配 ItemTemplate
属性到 {StaticResource MyListBoxItemsTemplateKey}
关于WPF UserControl 或 ControlTemplate...(不确定),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10018209/