无法将自定义 DependencyProperty 绑定到我的视图模型中的 属性

Can't bind a custom DependencyProperty to a property in my viewmodel

我有以下 DependencyProperty:

    public static readonly DependencyProperty RulerThicknessProperty = DependencyProperty.Register(
        "RulerThicknessProperty", typeof(Thickness), typeof(BoundaryLinesLayer),
        new PropertyMetadata(new Thickness(1), OnRulerThicknessChanged));

    public Thickness RulerThickness
    {
        get => (Thickness)GetValue(RulerThicknessProperty);
        set => SetValue(RulerThicknessProperty, value);
    }

    private static void OnRulerThicknessChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is BoundaryLinesLayer rt)
        {
            rt.PropertyChanged?.Invoke(rt, new PropertyChangedEventArgs(nameof(RulerThickness)));
        }
    }

Xaml 部分代码如下所示:

                    <layers:BoundaryLinesLayer
                        x:Name="Rulers"
                        BoundaryLines="{Binding Path=LeftAxisData.BoundaryLines}"
                        DefaultRulerThickness="1"
                        DraggableDraggingColor="{StaticResource CytivaGreenBrush}"
                        DraggableMouseOverColor="{StaticResource CytivaGreenBrush}"
                        DraggableMouseOverThickness="2"
                        ReadingBackground="{StaticResource StructureContainerBrush}"
                        RulerThickness="{Binding MouseOver, Converter={StaticResource MouseOverToCorrectRulerConverter}}"
                        XAxis="{Binding ElementName=InnerBottomAxis, Path=Axis}"
                        YAxis="{Binding ElementName=InnerLeftAxis, Path=Axis}">

我的视图模型中的 属性 如下所示:

    private bool _mouseOver;
    public bool MouseOver
    {
        get { return _mouseOver; }
        set 
        { 
            SetAndRaise(value, () => MouseOver, ref _mouseOver); 
        }
    }

为什么我不能在我的 Xaml 代码中将 RulerThickness dp 绑定到虚拟机中的 MouseOver 属性?我不断收到错误消息:“无法在 [=24= 类型的 'RulerThickness' 属性 上设置 A 'Binding'。A 'Binding' 只能在 DependencyProperty 上设置DependencyObject 的。”我在这里错过了什么?任何可以为我指明正确方向的 idea/thought 都非常感谢,或者如果有人可以告诉我有什么我不明白的地方。

您需要将注册码中的"RulerThicknessProperty"字符串参数更改为"RulerThickness",否则RulerThickness属性不会被识别为依赖项属性.您通常会使用 nameof(RulerThickness).

而不是使用字符串 litaral
public static readonly DependencyProperty RulerThicknessProperty = 
    DependencyProperty.Register(
        nameof(RulerThickness), typeof(Thickness), typeof(BoundaryLinesLayer),
        new PropertyMetadata(new Thickness(1), OnRulerThicknessChanged));