我在让简单的 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
时,一切正常,但使用返回 DataTemplate
的 ContentTemplateSelector
基于 TextBlock
,我遇到了和以前一样的错误。
我错过了什么?
最佳答案
如果您不创建模板,那么您应该使用 ContentControl
ContentPresenter
通常用作 ControlTemplate
的一部分 >内容控件
。
Remarks
Typically, you use the
ContentPresenter
directly within theControlTemplate
of aContentControl
to mark where the content to be presented appears.A
ContentPresenter
is often used to apply characteristics to text content, which are set into aContent
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 aContentPresenter
are similar to the properties of theTextElement
class. (TheTextElement
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
放置在 ContentControl
的 ControlTemplate
中时,它会自动显示模板化控件的内容。这意味着,如果您将 ControlTemplate
的 TargetType
设置为 Button,则 ContentPresenter
的 Content 属性将隐式绑定(bind)到使用该 ControlTemplate
的按钮。
要为 ContentPresenter
属性设置绑定(bind),您可能需要考虑使用 ContentSource
属性。 ContentSource
属性指向模板化父级的属性,并自动为关联的模板和模板选择器属性设置别名。
关于c# - ContentPresenter 在 UWP 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37533674/