Wpf UserControl通过RelativeSource Self访问DependencyProperty
我在用户控件中使用Wpf UserControl通过RelativeSource Self访问DependencyProperty,wpf,user-controls,dependency-properties,relativesource,Wpf,User Controls,Dependency Properties,Relativesource,我在用户控件中使用RelativeSourceSelf时遇到问题。我已经构建了两个用户控件,我认为它们在操作上是相同的,但一个可以工作,另一个不能。用户控件本身只包含一个标签,我想将其内容设置为控件的dependencProperty标题。当我将UserControl的DataContext设置为RelativeSourceSelf,并将标签绑定到Path=Title时,一切正常。但是,如果我将标签绑定到relativesourcefindancestor,AncestorType{x:Type
RelativeSource
Self时遇到问题。我已经构建了两个用户控件,我认为它们在操作上是相同的,但一个可以工作,另一个不能。用户控件本身只包含一个标签,我想将其内容设置为控件的dependencProperty
标题。当我将UserControl的DataContext
设置为RelativeSource
Self,并将标签绑定到Path=Title
时,一切正常。但是,如果我将标签绑定到relativesourcefindancestor,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>
假设您的Title属性的代码没有引起问题(因为它没有列出,所以无法判断),除了拼写之外,其他一切看起来都正常:
RelativeSource
->RelativeSource