开发者

Styling ListBox with Static Content

I have a set of static content that I want in a ListBox control.

<ListBox>
    <ListBox.Items>
        <ListBoxItem>
            <Image />
            <TextBlock Text="One" />
        </ListBoxItem>
        <ListBoxItem>
            <Image />
            <TextBlock Text="Two" />
        </ListBoxItem>
        <ListBoxItem>
            <Image />
            <TextBlock Text="Three" />
        </ListBoxItem>
    </ListBox.Items>
</ListBox>

How do I go about styling this? I know I can style each ListBoxItem individually, and I know how to style when data bound, but how do I style the a listb开发者_Python百科ox item template when using static content like this?


You can define the items as low-level objects and use data-templating, which may not be the same as styles but properties are only set once as well:

<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>

(To style the wrapping ListBoxItems you can try using an implicit style defined in the ListBox.Resources)


The following only works in WPF

Add a style to the resources of the ListBox and only set the TargetType and not the x:Key, it will be applied automatically.

You can even nest this automatic application using Resources, e.g.:

<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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜