2013-02-12 55 views
1

我一直在使用UserControl中的RelativeSource Self發生問題。我已經構建了兩個用戶控件,我認爲它們在操作上是相同的,但其中一個可以工作,另一個不可以。用戶控件本身只包含一個標籤,其內容我想設置爲控件的標題DependencyProperty。當我將UserControl的DataContext設置爲RelativeSource Self,並將標籤綁定到Path=Title時,一切正常。但是,如果我將標籤綁定到RelativeSource FindAncestor, AncestorType{x:Type UserControl}}, Path=Title,那麼它會因TargetInvocationException而失敗。UserControl通過RelativeSource訪問DependencyProperty自我

對我在做什麼錯的任何想法。

這是工作的用戶控件的XAML:

<UserControl x:Class="UserControlBinding.Controls.MyLabelControl1" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300" 
      DataContext="{Binding RelativeSource={RelativeSource Self}}"> 
    <Grid> 
     <Label Content="{Binding Path=Title}"></Label> 
    </Grid> 
</UserControl> 

這是代碼的XAML失敗

<UserControl x:Class="UserControlBinding.Controls.MyLabelControl2" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:local="clr-namespace:UserControlBinding.Controls" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"> 
    <Grid> 
     <Label Content="{Binding ReleativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MyLabelControl2}}, Path=Title}"></Label> 
    </Grid> 
</UserControl> 

回答

3

假設你的標題屬性的代碼不造成一個問題(可不知道,因爲它沒有列出)一切看起來都很好,除了拼寫:ReleativeSource - >RelativeSource

相關問題