What is difference between a ControlTemplate
and a DataTemplate
in WPF?
相关问题
- VNC control for WPF application
- WPF Binding from System.Windows.SystemParameters.P
- XAML: Applying styles to nested controls
- How can I add a horizontal line (“goal line”) for
- How to properly change a resource dictionary
ControlTemplate
DEFINES the visual appearance,DataTemplate
REPLACES the visual appearance of a data item.Example: I want to show a button from rectangular to circle form => Control Template.
And if you have complex objects to the control, it just calls and shows
ToString()
, withDataTemplate
you can get various members and display and change their values of the data object.ControlTemplate
- Changing the appearance of element. For exampleButton
can contain image and textDataTemplate
- Representing the underlying data using the elements.Very basically a
ControlTemplate
describes how to display a Control while aDataTemplate
describes how to display Data.For example:
A
Label
is a control and will include aControlTemplate
which says theLabel
should be displayed using aBorder
around some Content (aDataTemplate
or another Control).A
Customer
class is Data and will be displayed using aDataTemplate
which could say to display theCustomer
type as aStackPanel
containing twoTextBlocks
one showing the Name and the other displaying the phone number. It might be helpful to note that all classes are displayed usingDataTemplates
, you will just usually use the default template which is aTextBlock
with theText
property set to the result of the Object'sToString
method.ControlTemplate
: Represents control style.DataTemplate
: Represents data style(How would you like to show your data).All controls are using default control template that you can override through template property.
For example
Button
template is a control template.Button
content template is a data templateTypically a control is rendered for its own sake, and doesn't reflect underlying data. For example, a
Button
wouldn't be bound to a business object - it's there purely so it can be clicked on. AContentControl
orListBox
, however, generally appear so that they can present data for the user.A
DataTemplate
, therefore, is used to provide visual structure for underlying data, while aControlTemplate
has nothing to do with underlying data and simply provides visual layout for the control itself.A
ControlTemplate
will generally only containTemplateBinding
expressions, binding back to the properties on the control itself, while aDataTemplate
will contain standard Binding expressions, binding to the properties of itsDataContext
(the business/domain object or view model).Troels Larsen has a good explanation on MSDN forum