wpf WPF中控件模板和数据模板的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1340108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:55:32  来源:igfitidea点击:

Difference between Control Template and DataTemplate in WPF

wpfdatatemplatecontroltemplate

提问by Firoz

What is difference between a ControlTemplateand a DataTemplatein WPF?

WPF中的aControlTemplate和a有什么区别DataTemplate

回答by Matt Hamilton

Typically a control is rendered for its own sake, and doesn't reflect underlying data. For example, a Buttonwouldn't be bound to a business object - it's there purely so it can be clicked on. A ContentControlor ListBox, however, generally appear so that they can present data for the user.

通常,控件是为了它自己而呈现的,并不反映基础数据。例如,aButton不会绑定到一个业务对象——它在那里纯粹是为了可以点击它。甲ContentControl或者ListBox,然而,一般出现,使他们能够对用户显示数据。

A DataTemplate, therefore, is used to provide visual structure for underlying data, while a ControlTemplatehas nothing to do with underlying data and simply provides visual layout for the control itself.

DataTemplate因此,A用于为底层数据提供可视化结构,而 aControlTemplate与底层数据无关,只是为控件本身提供可视化布局。

A ControlTemplatewill generally only contain TemplateBindingexpressions, binding back to the properties on the control itself, while a DataTemplatewill contain standard Binding expressions, binding to the properties of its DataContext(the business/domain object or view model).

AControlTemplate通常只包含TemplateBinding表达式,绑定回控件本身的属性,而 aDataTemplate将包含标准绑定表达式,绑定到其属性DataContext(业务/域对象或视图模型)。

回答by Bryan Anderson

Very basically a ControlTemplatedescribes how to display a Control while a DataTemplatedescribes how to display Data.

基本上 aControlTemplate描述了如何显示控件,而 aDataTemplate描述了如何显示数据。

For example:

例如:

A Labelis a control and will include a ControlTemplatewhich says the Labelshould be displayed using a Borderaround some Content (a DataTemplateor another Control).

ALabel是一个控件,将包含一个ControlTemplate表示Label应该使用Border围绕某些内容(一个DataTemplate或另一个控件)显示的 a 。

A Customerclass is Data and will be displayed using a DataTemplatewhich could say to display the Customertype as a StackPanelcontaining two TextBlocksone showing the Name and the other displaying the phone number. It might be helpful to note that all classes are displayed using DataTemplates, you will just usually use the default template which is a TextBlockwith the Textproperty set to the result of the Object's ToStringmethod.

一个Customer类是数据,将使用 a 显示DataTemplate,可以说将Customer类型显示为StackPanel包含两个TextBlocks显示名称和另一个显示电话号码的类型。注意到所有类都使用 显示可能会有所帮助DataTemplates,您通常只使用默认模板,该模板TextBlockText属性设置为对象ToString方法的结果。

回答by onmyway133

Troels Larsenhas a good explanation on MSDN forum

Troels LarsenMSDN 论坛上有很好的解释

<Window x:Class="WpfApplication7.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
  <Window.Resources>
    <DataTemplate x:Key="ButtonContentTemplate">
      <StackPanel Orientation="Horizontal">
        <Grid Height="8" Width="8">
          <Path HorizontalAlignment="Stretch" 
           Margin="0,0,1.8,1.8" 
           VerticalAlignment="Stretch" Stretch="Fill" Stroke="#FF000000" 
           Data="M0.5,5.7 L0.5,0.5 L5.7,0.5"/>
          <Path HorizontalAlignment="Stretch" 
           Margin="2,3,0,0" 
           VerticalAlignment="Stretch" Stretch="Fill" Stroke="#FFFFFFFF" 
           Data="M3.2,7.5 L7.5,7.5 L7.5,3.5"/>
          <Path HorizontalAlignment="Stretch" 
           Margin="1.2,1.4,0.7,0.7" 
           VerticalAlignment="Stretch" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" 
           Data="M2.5,2.5 L7.5,7.5"/>
          <Path HorizontalAlignment="Stretch" 
           Margin="1.7,2.0,1,1" 
           VerticalAlignment="Stretch" Stretch="Fill" Stroke="#FF000000" 
           Data="M3,7.5 L7.5,7.5 L7.5,3.5"/>
          <Path HorizontalAlignment="Stretch" 
           Margin="1,1,1,1" 
           VerticalAlignment="Stretch" Stretch="Fill" Stroke="#FFFFFFFF" 
           Data="M1.5,6.5 L1.5,1 L6.5,1.5"/>
        </Grid>
        <ContentPresenter Content="{Binding}"/>
      </StackPanel>
    </DataTemplate>
    <ControlTemplate TargetType="Button" x:Key="ButtonControlTemplate">
      <Grid>
        <Ellipse Fill="{TemplateBinding Background}"/>
        <ContentPresenter HorizontalAlignment="Center"
              VerticalAlignment="Center"/>
      </Grid>
    </ControlTemplate>
  </Window.Resources>
  <StackPanel>
    <Button Template="{StaticResource ButtonControlTemplate}" ContentTemplate="{StaticResource ButtonContentTemplate}" Content="1"/>
    <Button Template="{StaticResource ButtonControlTemplate}" ContentTemplate="{StaticResource ButtonContentTemplate}" Content="2"/>
    <Button Template="{StaticResource ButtonControlTemplate}" ContentTemplate="{StaticResource ButtonContentTemplate}" Content="3"/>
  </StackPanel>
</Window>

(Templates blatently stolen from http://msdn.microsoft.com/en-us/library/system.windows.controls.controltemplate.aspxand http://msdn.microsoft.com/en-us/library/system.windows.controls.contentcontrol.contenttemplate%28VS.95%29.aspxrespectively)

Anyway, the ControlTemplate decides how the Button itself looks, while the ContentTemplate decides how the Content of the button looks. So you could bind the content to one of you data classes and have it present itself however you wanted it.

<Window x:Class="WpfApplication7.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
  <Window.Resources>
    <DataTemplate x:Key="ButtonContentTemplate">
      <StackPanel Orientation="Horizontal">
        <Grid Height="8" Width="8">
          <Path HorizontalAlignment="Stretch" 
           Margin="0,0,1.8,1.8" 
           VerticalAlignment="Stretch" Stretch="Fill" Stroke="#FF000000" 
           Data="M0.5,5.7 L0.5,0.5 L5.7,0.5"/>
          <Path HorizontalAlignment="Stretch" 
           Margin="2,3,0,0" 
           VerticalAlignment="Stretch" Stretch="Fill" Stroke="#FFFFFFFF" 
           Data="M3.2,7.5 L7.5,7.5 L7.5,3.5"/>
          <Path HorizontalAlignment="Stretch" 
           Margin="1.2,1.4,0.7,0.7" 
           VerticalAlignment="Stretch" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" 
           Data="M2.5,2.5 L7.5,7.5"/>
          <Path HorizontalAlignment="Stretch" 
           Margin="1.7,2.0,1,1" 
           VerticalAlignment="Stretch" Stretch="Fill" Stroke="#FF000000" 
           Data="M3,7.5 L7.5,7.5 L7.5,3.5"/>
          <Path HorizontalAlignment="Stretch" 
           Margin="1,1,1,1" 
           VerticalAlignment="Stretch" Stretch="Fill" Stroke="#FFFFFFFF" 
           Data="M1.5,6.5 L1.5,1 L6.5,1.5"/>
        </Grid>
        <ContentPresenter Content="{Binding}"/>
      </StackPanel>
    </DataTemplate>
    <ControlTemplate TargetType="Button" x:Key="ButtonControlTemplate">
      <Grid>
        <Ellipse Fill="{TemplateBinding Background}"/>
        <ContentPresenter HorizontalAlignment="Center"
              VerticalAlignment="Center"/>
      </Grid>
    </ControlTemplate>
  </Window.Resources>
  <StackPanel>
    <Button Template="{StaticResource ButtonControlTemplate}" ContentTemplate="{StaticResource ButtonContentTemplate}" Content="1"/>
    <Button Template="{StaticResource ButtonControlTemplate}" ContentTemplate="{StaticResource ButtonContentTemplate}" Content="2"/>
    <Button Template="{StaticResource ButtonControlTemplate}" ContentTemplate="{StaticResource ButtonContentTemplate}" Content="3"/>
  </StackPanel>
</Window>

(模板公然从 http://msdn.microsoft.com/en-us/library/system.windows.controls.controltemplate.aspxhttp://msdn.microsoft.com/en-us/library/system.windows .controls.contentcontrol.contenttemplate%28VS.95%29.aspx

无论如何,ControlTemplate 决定按钮本身的外观,而 ContentTemplate 决定按钮的内容的外观。因此,您可以将内容绑定到其中一个数据类,并让它以您想要的方式呈现。

回答by sayed saad

ControlTemplate: Represents control style.

ControlTemplate: 代表控件样式。

DataTemplate: Represents data style(How would you like to show your data).

DataTemplate: 表示数据样式(您希望如何显示您的数据)。

All controls are using default control template that you can override through template property.

所有控件都使用您可以通过模板属性覆盖的默认控件模板。

For example
Buttontemplate is a control template. Buttoncontent template is a data template

例如
Button模板是一个控件模板。 Button内容模板是一个数据模板

<Button   VerticalAlignment="Top" >
    <Button.Template>
        <ControlTemplate >
            <Grid>
                <Rectangle Fill="Blue" RadiusX="20" RadiusY="20"/>
                <Ellipse Fill="Red" />
                <ContentPresenter Content="{Binding}">
                    <ContentPresenter.ContentTemplate>
                        <DataTemplate>
                        <StackPanel Orientation="Horizontal" Height="50">
                            <TextBlock Text="Name" Margin="5"/>
                                <TextBox Text="{Binding UserName, Mode=TwoWay}" Margin="5" Width="100"/>
                            <Button Content="Show Name" Click="OnClickShowName" />
                        </StackPanel>
                    </DataTemplate>
                    </ContentPresenter.ContentTemplate>
                </ContentPresenter>
            </Grid>
        </ControlTemplate>
    </Button.Template>
</Button>

public String UserName
{
    get { return userName; }
    set
    {
        userName = value;
        this.NotifyPropertyChanged("UserName");
    }
}

回答by Syed

ControlTemplate- Changing the appearance of element. For example Buttoncan contain image and text

ControlTemplate- 改变元素的外观。例如Button可以包含图像和文本

DataTemplate- Representing the underlying data using the elements.

DataTemplate- 使用元素表示底层数据。

回答by nihnih

ControlTemplateDEFINES the visual appearance, DataTemplateREPLACES the visual appearance of a data item.

ControlTemplate定义视觉外观,替换DataTemplate数据项的视觉外观。

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(), with DataTemplateyou can get various members and display and change their values of the data object.

如果您有复杂的控件对象,它只调用和显示ToString()DataTemplate您可以获取各种成员并显示和更改数据对象的值。

回答by Ashi

All of the above answers are great but there is a key difference that was missed. That helps make better decisions about when to use what. It is ItemTemplateproperty:

以上所有答案都很好,但有一个关键的区别被遗漏了。这有助于更好地决定何时使用什么。它是ItemTemplate财产:

  • DataTemplate is used for elements that provide ItemTemplate propertyfor you to replace its items' content using DataTemplates you define previously according to bound data through a selector that you provide.

  • But if your control does not provide this luxury for youthen you still can use a ContentViewthat can display its content from predefined ControlTemplate. Interestingly, you can change the ControlTemplateproperty of your ContentViewat runtime. One more thing to note that unlike controls with ItemTemplateproperty, you cannot have a TemplateSelectorfor this (ContentView) control. However, you still can create triggers to change the ControlTemplateat runtime.

  • DataTemplate 用于提供 ItemTemplate 属性的元素,DataTemplate根据您提供的选择器根据绑定数据使用您之前定义的 s替换其项目的内容。

  • 但是,如果您的控件没有为您提供这种奢侈,那么您仍然可以使用ContentView可以从预定义的ControlTemplate. 有趣的是,您可以在运行时更改您的ControlTemplate属性ContentView。需要注意的另一件事是,与具有ItemTemplate属性的控件不同,您不能拥有一个TemplateSelectorfor this (ContentView) 控件。但是,您仍然可以创建触发器来ControlTemplate在运行时更改。