How to add a border to an item in a ItemsControl?

Lucifer picture Lucifer · Jan 29, 2012 · Viewed 12.7k times · Source

I am trying to set a border to each item from a items control. Following is my XAML code. But this doesn't work.

<ItemsControl.ItemContainerStyle>
    <Style>
        <Setter Property="Control.BorderThickness" Value="5" />
        <Setter Property="Control.BorderBrush" Value="Black" />
    </Style>
</ItemsControl.ItemContainerStyle>

Answer

H.B. picture H.B. · Jan 29, 2012

The container in an ItemsControl is a ContentPresenter which is not a control, this style will not do anything. You could create an ItemsTemplate containing a Border.

Alternatively you can change the ContentTemplate in the ItemContainerStyle:

<ItemsControl.ItemContainerStyle>
    <Style TargetType="ContentPresenter">
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <Border BorderBrush="Black" BorderThickness="5">
                        <ContentPresenter Content="{Binding}"/>
                    </Border>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ItemsControl.ItemContainerStyle>

(Note: This is a real alternative in the sense that it does the exact same thing, so i would use the ItemTemplate as it is a lot less verbose, saves you three tags (Style, Setter, Setter.Value))