2016-05-30 2 views
1

私は期待どおりに簡単なContentPresenterを動作させるのに問題があります。私はContentPresenterがちょうどTextBlockTextとプロパティを作成することを期待ContentPresenterはどのようにUWPで動作しますか?

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

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

私は新しいUWPプロジェクトを開始すると、

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

MainPage内容を変更

、それがコードビハインドだ設定「Hello World」に設定します。少なくともそれはWPFでそのように動作します。

代わりに、何も示されていない、と私は出力のバインディングエラーを持っている:

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に設定すると、すべて正常に機能しますが、TextBlockに基づいてDataTemplateを返すContentTemplateSelectorを使用すると、前と同じエラーが発生します。

私には何が欠けていますか?

+1

代わりにContentControlに切り替えるまで、私はUWPのContentPresenterに大きな問題がありました。あなたのユースケースに合っているかどうかはわかりませんが、試してみてください –

答えて

4

テンプレートを作成していない場合は、ContentControlを使用してください。ContentPresenterは、通常のContentControlの一部として使用されます。あなたがContentControlControlTemplateContentPresenterを配置すると、それは自動的にテンプレートコントロールの内容を表示する

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.)

備考。これは、ControlTemplateTargetTypeをButtonに設定した場合、ContentPresenterのContentプロパティは、そのControlTemplateを使用しているButtonのコンテンツに暗黙的にバインドされていることを意味します。

ContentPresenterプロパティのバインディングを設定するには、ContentSourceプロパティを使用することを検討してください。 ContentSourceプロパティは、テンプレートされた親のプロパティを指すだけでなく、関連付けられたテンプレートとテンプレートセレクタのプロパティを自動的にエイリアスします。

関連する問題