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).
You use the ItemTemplate to specify the visualization of the data objects. If your ItemsControl is bound to a collection object and you do not provide specific display instructions using a DataTemplate, the resulting UI of each item is a string representation of each object in the underlying collection.
ItemsSource can be data bound to any sequence that implements the IEnumerable interface, although the type of collection used does determine the way in which the control is updated when items are added to or removed. When ItemsSource is set, the Items property cannot be used to control the displayed values.
A data template can contain elements that are each bound to a data property along with additional markup that describes layout, color and other appearance. DataTemplate is, basically, used to specify the appearance of data displayed by a control not the appearance of the control itself.
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 DataTemplate
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With