Search code examples
c#wpfxamldata-binding

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


I have the following 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)));
        }
    }

and part of the Xaml-code looks like this:

                    <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}">

The property in my viewmodel looks like this:

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

Why can't I in my Xaml-code bind the RulerThickness dp to the MouseOver property in my vm? I keep getting the error message: "A 'Binding' cannot be set on the 'RulerThickness' property of type 'BoundaryLinesLayer'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject." What am I missing here? Any idea/thought that can point me in the right direction is very much appreciated, or if someone could just tell me that there's something I haven't understood.


Solution

  • You need to change the "RulerThicknessProperty" string argument to "RulerThickness" in the registration code, otherwise the RulerThickness property isn't recognized as a dependency property. Instead of using a string litaral, you would typically use nameof(RulerThickness).

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