I have a problem getting a simple ContentPresenter to work as I expect.
When I start a new UWP project, change the MainPage content to
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ContentPresenter Content="{Binding TheContent}" />
</Grid>
and set it's code-behind to
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.DataContext = new ViewModel();
}
}
public class ViewModel
{
public string TheContent { get { return "Hello World."; } }
}
I expect the ContentPresenter to just create a TextBlock with Text property set to "Hello World". At least it works that way in WPF.
Instead, nothing is shown, and I have a Binding error in the output:
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')
This looks to me, that the ContentPresenter tries to render it's content with the page it is located on?
When I explicitly set the ContentTemplate to a TextBlock, everything works fine, but using a ContentTemplateSelector that return a DataTemplate based on a TextBlock, I have the same error as before.
What am I missing?
If you are not creating a template then you should use the ContentControl The ContentPresenter is typically used as part of ControlTemplate of aContentControl.
Referencing:
Remarks
Typically, you use the
ContentPresenterdirectly within theControlTemplateof aContentControlto mark where the content to be presented appears.A
ContentPresenteris often used to apply characteristics to text content, which are set into aContentproperty 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 aContentPresenterare similar to the properties of theTextElementclass. (TheTextElementclass 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.)
Remarks
When you place a ContentPresenter in the ControlTemplate of a ContentControl, it automatically displays the Content of the templated control. This means that if you set the TargetType of your ControlTemplate to be Button, the Content property of the ContentPresenter is implicitly bound to the Content of the Button that is using that ControlTemplate.
To set up bindings for the ContentPresenter properties, you may want to consider using the ContentSource property. The ContentSource property points to a property on the templated parent as well as aliases the associated template and template selector properties automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With