2016-12-15 11 views
1

私はContentObjectプロパティを持つユーザーコントロールを持っており、カスタムコンテンツの指定に使用しています。メインウィンドウで、依存プロパティにバインドされたネストされたラベルを作成しました。私はRelativeSourceでそれをバインドする場合は正常に動作しますが、私は名前で要素を参照する場合は、何らかの理由でそれは動作しません:ContentPresenter子要素を外部コントロールに名前でバインドできません。

MainWindow.xaml:

<Window x:Class="TestContentPresenter.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:TestContentPresenter" 
     Title="MainWindow" Height="350" Width="525" Name="MyWindow"> 
    <Grid> 
     <local:MyUserControl> 
      <local:MyUserControl.ContentObject> 
       <!--<TextBlock Text="{Binding MyText, ElementName=MyWindow}"/>--> 
       <TextBlock Text="{Binding MyText, RelativeSource={RelativeSource AncestorType=Window}}"/> 
      </local:MyUserControl.ContentObject> 
     </local:MyUserControl> 
    </Grid> 
</Window> 

UserControl.xaml:

<UserControl x:Class="TestContentPresenter.MyUserControl" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:local="clr-namespace:TestContentPresenter" 
      Height="300" Width="300" Name="MainControl"> 
    <StackPanel> 
     <ContentPresenter Content="{Binding ContentObject, ElementName=MainControl}"/> 
    </StackPanel> 
</UserControl> 

メインウィンドウにはMyText依存関係プロパティがあり、コメント行は動作しません。私はこれが名前のスコープと関係があると思われますが、何か間違っているのですか?

答えて

1

あなたは本当に間違っているわけではありません。TextBlockのTextプロパティへのバインドが解決されるまでには、範囲内に「MyWindow」という名前の要素はありません。 UserControlのContentObjectプロパティをTextBlockに設定しますが、UserControlが最終的にレンダリングするときには、「MyWindow」という名前について何も知らないことになります。

TextBlockには常に親ウィンドウが存在するため、ElementNameをRelativeSource(既に発見したもの)に置き換えるだけで解決できます。 ElementNameは機能しません。

+0

WindowのrelativeSourceへのバインディングが適切でない別のユーザーコントロール内でこれを使用するとどうなりますか? – Gui

関連する問題