【问题标题】:Can't bind a custom DependencyProperty to a property in my viewmodel [duplicate]无法将自定义 DependencyProperty 绑定到我的视图模型中的属性 [重复]
【发布时间】:2022-01-17 05:10:40
【问题描述】:

我有以下 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 绑定到我的 vm 中的 MouseOver 属性?我不断收到错误消息:“无法在 'BoundaryLinesLayer' 类型的 'RulerThickness' 属性上设置 'Binding'。只能在 DependencyObject 的 DependencyProperty 上设置'Binding'。”我在这里想念什么?非常感谢任何可以为我指明正确方向的想法/想法,或者如果有人能告诉我有些东西我不明白。

【问题讨论】:

    标签: c# wpf xaml data-binding


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多