2010-11-19 18 views
0

私はUserControl Editorを持っていて、TextBoxを持っているとします。プロパティーはContentです。ここでは、テキストコンテンツを静的な値「Hey」に設定しています。UserControlのテキストボックスが正しくレンダリングされない

<UserControl x:Class="WpfApplication1.Editor" ...> 
    <TextBox Text="Hey" /> 
    <!--<TextBox Text="{Binding Content}" />--> 
</UserControl> 

次に、このすべてを表示するウィンドウがあります。

<Window x:Class="WpfApplication1.Window1" ...> 
    <StackPanel> 
     <local:Editor Content="Heya" /> 
    </StackPanel> 
</Window> 

私はそれを実行すると、私は

alt text

そのもないのTextBoxを取得しますか?そして、なぜコンテンツを<local:Editor />に設定するのですか?私はCleanを試しました&ソリューションを再構築しても、私はまだこの奇妙なことがあります。

答えて

2

問題


十分にシンプル。 A UserControlは実際にはContentControlであるため、Contentという名前の依存関係プロパティがあります。このプロパティを設定すると、ContentControlの内容全体が設定されます。 Contentプロパティはデフォルトプロパティです(MSDNのWPFの既定のプロパティを参照してください)。

<UserControl x:Class="WpfApplication1.Editor" ...> 

    <!-- Here, you set the Content property (because it is 
    the default one) of the UserControl as a TextBox with 
    the text "Hey". --> 

    <TextBox Text="Hey" /> 
</UserControl> 

は上記とコードの下の比較:


ソリューション...

<!-- Here, the Content property is explicitly set. --> 
<local:Editor Content="Heya" /> 

どちらの場合も、あなたは異なる内容のContentプロパティを定義


、あなたの問題を解決するためのインスタンスTextContentという名前EditorでカスタムDependencyPropertyを定義し、次の操作を行う:

<UserControl x:Class="WpfApplication1.Editor" ...> 
    <TextBox Text="{Binding TextContent, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" /> 
</UserControl> 

そして最後に

<local:Editor TextContent="Heya" /> 
+0

ああ...、傷のようにずっと後に私の頭! –

関連する問題