【问题标题】:Difference between Style and Presenter?样式和演示者之间的区别?
【发布时间】:2020-11-16 20:23:26
【问题描述】:

您能告诉我 Style 和 Presenter 之间的主要区别是什么吗?何时或为何使用其中一种?

看看sample from Microsoft,它们的用途似乎完全相同。

【问题讨论】:

    标签: .net wpf xaml uwp uwp-xaml


    【解决方案1】:

    您使用Style 来修改FrameworkElement 的属性。 Style 可以应用于单个元素或多个元素。

    要将特定范围内的所有Button元素的字体大小更改为28,将Border更改为红色,您可以创建以下Style

    <Style TargetType="Button">
      <Setter Property="FontSize" Value="28" />
      <Setter Property="BorderBrush" Value="Red" />
      <Setter Property="BorderThickness" Value="2" />
    </Style>
    

    但是Button不仅具有BorderBrushBorderThicknessContent等属性,而且还具有外观。控件必须以某种方式呈现属性值的外观。

    此视觉外观由ControlTemplate 描述。它定义了Border 以及Border 的确切位置以及Content 值的放置位置。

    要放置内容,ButtonControlTemplate 或每个其他 ContentControl 都包含 ContentPresenter。该演示者负责显示ContentControl 的数据:ContentControl.Content 值。

    Button 最简单的视觉效果可能如下所示:

    <Style TargetType="Button">
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="Button">
      
            <!-- Add a Border and bind it to the Button's properties -->
            <Border BorderBrush="{TemplateBinding BorderBrush}"
                    BorderThickness="{TemplateBinding BorderThickness}">
    
              <!-- 
                Show the content of the Button (the value of the Content Property).
                By default the ContentPresenter of a ContentControl will automatically
                bind to the Content property
              -->
              <ContentPresenter />
            </Border>
          </ContentPresenter>
        </Setter.Value>
      </Setter>
    </Style>
    

    ItemsControl 将显示项目而不是简单的内容,即ItemsControl.Items 属性的数据值。当然ItemsControl 使用不同类型的presenter,因为它需要显示不同的数据,例如项目集合。但目的完全相同:呈现数据。

    Button 的数据是 Content,例如“保存”文本。
    ItemsControl 的数据是单个项目,即 Items 属性的值。

    除了指定内容的位置外,演示者还将DataTemplates 应用于其显示的数据。您使用DataTemplate 来定义数据本身的外观。为此,ContentControl 公开了 ContentTemplate 属性,ItemsControl 公开了 ItemTemplate 属性。

    我不想写新的文档,所以就到此为止。
    你绝对应该阅读更多关于它的信息。由于 WPF 和 UWP 遵循相同的概念,您可以阅读这两个框架的文档。

    Styles and templates in WPF
    Control templates
    Data Templating Overview

    【讨论】:

      【解决方案2】:

      这是两个非常不同的东西。

      listviewitempresenter 是 uwp 而不是 wpf。

      你可以在这里看到命名空间:

      https://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.controls.primitives.listviewitempresenter?view=winrt-19041

      Windows.UI.Xaml.Controls 表示 uwp。

      它显示了一个列表视图项的内容。它继承自内容演示者,这可能是一种更清晰的思考方式。内容演示者是一种用于将要显示的内容的占位符。 将显示的 UI 事物的容器。

      样式是一种可重复使用的标记,可以将相同的值应用于它所应用的多个元素。很像css风格。它通过应用于某种依赖对象而产生效果。从技术上讲,这可以是任何依赖对象,但实际上通常是一段 UI。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多