代码如下
1.MainWindow.cs
<StackPanel>
<Button x:Name="HelloButton" Width="100">Hello</Button>
<lib:TestControl Width="100" TestValue="{Binding ElementName=HelloButton,Path=Width}">
<lib:TestControl.Some>
<lib:SomePropertyClass Inner="{Binding ElementName=HelloButton,Path=Width}"/>
</lib:TestControl.Some>
</lib:TestControl>
</StackPanel>
2.TestControl.cs
public class TestControl : Control
{
static TestControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TestControl), new FrameworkPropertyMetadata(typeof(TestControl)));
}
public static readonly DependencyProperty TestValueProperty = DependencyProperty.Register("TestValue", typeof(int), typeof(TestControl));
public int TestValue
{
get => (int)GetValue(TestValueProperty);
set => SetValue(TestValueProperty, value);
}
public static readonly DependencyProperty SomeProperty = DependencyProperty.Register("Some", typeof(SomePropertyClass), typeof(TestControl));
public SomePropertyClass Some
{
get => (SomePropertyClass)GetValue(SomeProperty);
set => SetValue(SomeProperty, value);
}
}
public class SomePropertyClass : DependencyObject
{
public static readonly DependencyProperty InnerProperty = DependencyProperty.Register("Inner", typeof(int), typeof(SomePropertyClass));
public int Inner
{
get => (int)GetValue(InnerProperty);
set => SetValue(InnerProperty, value);
}
}
3.TestControl.xaml
<Style TargetType="{x:Type local:TestControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:TestControl}">
<StackPanel>
<Button Content="{TemplateBinding TestValue}"/>
<Button Content="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},Path=Some.Inner}"/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
需要“TestValue”属性绑定,但为什么“Inner”属性绑定会导致错误?
'系统.Windows.数据错误:2:找不到目标元素的控制FrameworkElement或FrameworkContentElement。BindingExpression:Path=Width; String =null;目标元素是'SomePropertyClass'(HashCode=63183526);目标属性为“Inner”(类型为“Int 32”)
1条答案
按热度按时间gpnt7bae1#
为什么'Inner'属性绑定会导致错误?
因为搜索算法找不到元素
HelloButton
。x:Reference
应该工作:SomePropertyClass
与HelloButton
不在同一个namescope中,但TestControl
在。What is the difference between x:Reference and ElementName?