RelativeSource
UserControl で Self を使用すると問題が発生します。動作が同じと思われる 2 つの UserControls を構築しましたが、1 つが機能し、もう 1 つが機能しません。ユーザー コントロール自体は、コントロールのDependencyProperty
タイトルに設定するコンテンツのラベルだけで構成されています。DataContext
UserControl の をSelfに設定しRelativeSource
、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>