我在 ListBox
控件中有一组我想要的静态内容。
<ListBox>
<ListBox.Items>
<ListBoxItem>
<Image />
<TextBlock Text="One" />
</ListBoxItem>
<ListBoxItem>
<Image />
<TextBlock Text="Two" />
</ListBoxItem>
<ListBoxItem>
<Image />
<TextBlock Text="Three" />
</ListBoxItem>
</ListBox.Items>
</ListBox>
我该如何设计这个?我知道我可以单独设置每个
ListBoxItem
的样式,并且我知道如何在数据绑定(bind)时设置样式,但是在使用这样的静态内容时如何设置列表框项模板的样式? 最佳答案
您可以将项目定义为低级对象并使用数据模板,这可能与样式不同,但属性也只设置一次:
<ListBox xmlns:sys="clr-namespace:System;assembly=mscorlib">
<ListBox.Items>
<sys:String>one</sys:String>
<sys:String>two</sys:String>
<sys:String>three</sys:String>
</ListBox.Items>
<ListBox.ItemTemplate>
<DataTemplate>
<!-- "Style" this at will -->
<StackPanel>
<Image />
<TextBlock Text="{Binding}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
(要设置包装 ListBoxItems 的样式,您可以尝试使用
ListBox.Resources
中定义的隐式样式)以下仅适用于 WPF
给 ListBox 的资源添加一个样式,只设置
TargetType
而不是 x:Key
,它会自动应用。您甚至可以使用 Resources 嵌套这个自动应用程序,例如:
<ListBox>
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Resources>
<Style TargetType="{x:Type Image}">
<Setter Property="Width" Value="100"/>
</Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="Blue"/>
</Style>
</Style.Resources>
</Style>
</ListBox.Resources>
<!-- Items here -->
</ListBox>
关于xaml - 带有静态内容的样式列表框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5555109/