c# - ContentPresenter 在 UWP 中如何工作?

标签 c# xaml uwp

我在让简单的 ContentPresenter 按预期工作时遇到问题。

当我开始一个新的 UWP 项目时,将 MainPage 内容更改为

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <ContentPresenter Content="{Binding TheContent}" />
</Grid>

并将它的代码隐藏设置为

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
        this.DataContext = new ViewModel();
    }        
}

public class ViewModel
{
    public string TheContent { get { return "Hello World."; } }
}

我希望 ContentPresenter 只创建一个 TextBlock 并将 Text 属性设置为“Hello World”。至少它在 WPF 中是这样工作的。

相反,没有显示任何内容,并且输出中出现绑定(bind)错误:

Error: BindingExpression path error: 'TheContent' property not found on 'Windows.Foundation.IReference`1'. BindingExpression: Path='TheContent' DataItem='Windows.Foundation.IReference`1'; target element is 'Windows.UI.Xaml.Controls.ContentPresenter' (Name='null'); target property is 'Content' (type 'Object')

在我看来,ContentPresenter 试图用它所在的页面呈现它的内容? 当我将 ContentTemplate 显式设置为 TextBlock 时,一切正常,但使用返回 DataTemplateContentTemplateSelector基于 TextBlock,我遇到了和以前一样的错误。

我错过了什么?

最佳答案

如果您不创建模板,那么您应该使用 ContentControl ContentPresenter 通常用作 ControlTemplate 的一部分 >内容控件

Referencing:

Remarks

Typically, you use the ContentPresenter directly within the ControlTemplate of a ContentControl to mark where the content to be presented appears.

A ContentPresenter is often used to apply characteristics to text content, which are set into a Content property using only a string for the text (or some indirect equivalent such as a Binding or a RESX resource). For this reason the properties of a ContentPresenter are similar to the properties of the TextElement class. (The TextElement class is a base class for several elements that aren't controls but are used to format the text that might appear in a control or layout container.)

备注

当您将 ContentPresenter 放置在 ContentControlControlTemplate 中时,它会自动显示模板化控件的内容。这意味着,如果您将 ControlTemplateTargetType 设置为 Button,则 ContentPresenter 的 Content 属性将隐式绑定(bind)到使用该 ControlTemplate 的按钮。

要为 ContentPresenter 属性设置绑定(bind),您可能需要考虑使用 ContentSource 属性。 ContentSource 属性指向模板化父级的属性,并自动为关联的模板和模板选择器属性设置别名。

关于c# - ContentPresenter 在 UWP 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37533674/

相关文章:

c# - 如何在 C# 中创建带有 URI 和时间输入的列表

c# - UWP SQL 连接错误 [c#]

c# - 如何在创建并启动所有线程之前阻止新线程

c# - 不能向表中添加一个以上的用户。标识插入设置为关闭

c# - 如何调用 Creator 方法的

c# - 即使内容比容器高,WPF 控件也会对齐到底部

C# 应用程序 - 如何在 xaml 表单中显示网站?

wpf - Surface 中的交互式 3D 对象

c# - 无法在 .NET SignalR 客户端 HubConnection(dotnet 核心/signalr 2.2)上设置连接超时

javascript - 无法在 JavaScript 中为 Windows.Web.Http.HttpClient 添加超时