UserControl通过RelativeSource Self访问DependencyProperty

时间:2013-02-12 18:31:15

标签: wpf user-controls dependency-properties relativesource

我在UserControl中使用RelativeSource Self时出现问题。我已经构建了两个我认为在操作上相同的UserControl,但是一个有效,另一个没有。用户控件本身只包含一个标签,其内容我想设置为控件的DependencyProperty标题。当我将UserControl的DataContext设置为RelativeSource Self,并将Label绑定到Path=Title时,一切正常。但是,如果我将Label绑定到RelativeSource FindAncestor, AncestorType{x:Type UserControl}}, Path=Title,则它会因TargetInvocationException而失败。

对我做错了什么的想法。

这是UserControl的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>

1 个答案:

答案 0 :(得分:3)

假设你的Title属性的代码没有引起问题(由于它没有列出而无法分辨)除了拼写之外,其他一切看起来都不错:ReleativeSource - &gt; RelativeSource