wpf 为什么自定义控件绑定会导致错误?

guykilcj  于 2023-05-08  发布在  其他
关注(0)|答案(1)|浏览(211)

代码如下
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”)

gpnt7bae

gpnt7bae1#

为什么'Inner'属性绑定会导致错误?
因为搜索算法找不到元素HelloButtonx:Reference应该工作:

<lib:SomePropertyClass Inner="{Binding Path=Width,Source={x:Reference HelloButton}}"/>

SomePropertyClassHelloButton不在同一个namescope中,但TestControl在。
What is the difference between x:Reference and ElementName?

相关问题