views:

58

answers:

1

Hi,

I'm quite new to the WPF world and I'm having some problems with templating items in an ItemsControl. What I need is to template elements (mostly buttons) inside an ItemsControl (or the like).

If I'm using the following XAML code ...

<ItemsControl>
    <ItemsControl.ItemTemplate>
        <DataTemplate DataType="{x:Type Button}">
                <Border BorderBrush="AliceBlue" 
                        BorderThickness="3">
                    <TextBlock Text="Templated!"/>        
                </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <Button>Not templated</Button>
    <TextBlock>Text not templated</TextBlock>
</ItemsControl>

... I get this result: http://img444.imageshack.us/img444/2167/itemscontrolnottemplate.gif

The ItemsControl did not apply the template to either the Button nor to the TextBlock control. If I change the ItemsControl into a ListBox like this:

<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate DataType="{x:Type Button}">
                <Border BorderBrush="AliceBlue" 
                        BorderThickness="3">
                    <TextBlock Text="Templated!"/>        
                </Border>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <Button>Not templated</Button>
    <TextBlock>Text not templated</TextBlock>
</ListBox>

... then I'm getting this result: img814.imageshack.us/img814/6204/listboxtoomuchtemplatin.gif

Now the template is applied to BOTH the child controls (even while I set the DataType to be Button only).

+1  A: 

It's difficult to infer what you're trying to do, but see if this helps...

A plain old ItemsControl won't wrap its children in a container if they're already UI elements. A ListBox, on the other hand, requires its children to be wrapped in a ListBoxItem.

If the item is wrapped, then the ItemTemplate will be applied. If the item is not wrapped, the ItemTemplate may as well not exist.

You almost always want to be adding data items to your ItemsControl, not UI elements. You then associate DataTemplates with those data elements to define what UI elements are used to render them.

I think explaining your end goal would be necessary to help further.

HTH,
Kent

Kent Boogaart
Thanks! That makes it clear.
null