WPF: The ItemsPanelTemplate - controlling how ListBox/ComboBox etc. render their children

来源:百度文库 编辑:神马文学网 时间:2024/07/07 17:02:53
Posted on3/5/2007 @ 1:21 AMin#WPF|0 comments|3870 views
This post is in continuation to anexplanation on WPF Templates.
1.ControlTemplate- You use this, when you want to completely redefine the visualappearance of any control. Say, you don‘t want a radiobutton to looklike a radiobutton - you want it to look like a smiley instead. Smilingmeans Checked, and Frowning means Unchecked. You could easily acheivethis using ControlTemplate.
2.ItemsPanelTemplate -Is a rather simple kind of template, it lets you control the appearanceof the "ItemsPanel" property defined by "ItemsControl" on elements suchas ListBox or ComboBox.
3.DataTemplate- is probably the most common kind of template you will use. It letsyou change how "Content" is rendered on any control. So if you have anobject called "Customer" and you want to define a standard look andfeel for "Customer" - you‘d use DataTemplate.
I have been talking about WPF Templates for a while now.
First,I talked about what WPF Templates are.
Then I demonstratedwhat a ControlTemplate is,it lets you render out completely custom UI for a control. As anexample, I took a bare "Control", and databound it with"System.DateTime", and I got a UI that looked like this -

The above was defined asa completely custom ControlTemplate.
Next, I defined a custom business object that was a collection of"LocalTime". LocalTime had two public properties - String (Place) andTime (DateTime). The idea being, using a DataTemplate that used theabove Clock ControlTemplate, I was able to convert a UI that lookedlike this -

.. into a UI that looked like this -

How exactly I did that,can be found here.
The final thing I wanted to talk about as far as templates go is, "How to make those clocks appear horizontally?"
Okay, so the DataTemplate lets me control an individual ListItem‘slooks. But if I wanted to control the ItemsPanel that renders all ofthe ListItems, I‘d have to use a ItemsPanelTemplate.
This is so darned simple to do, barely 2 steps involved -
a) Define the ItemsPanelTemplate in the resources.



b) Specify that the ListBox should use this ItemsPanel instead -
ItemsSource="{Binding Source={StaticResource localTimes}}"
ItemTemplate="{StaticResource ShowTime}"
ItemsPanel="{StaticResource HorizontalClocks}"
>

Thats it! Run the application, here is how it looks now -

Great, now put that in your Hotel, and you have your very own multi million $ hotel attracting international travellers ready.