【问题标题】:Setting a property in the ViewModel with a read-only dependency property from the View在 ViewModel 中使用 View 中的只读依赖项属性设置属性
【发布时间】:2013-02-01 16:53:24
【问题描述】:

我一直在尝试遵循a StackOverflow post 以及官方documentation on MSDN 来实现一个只读的依赖属性,该属性是由 ViewModel 使用的 WPF Canvas 控件的子类。

我已将 Canvas 的子类定义为:

public class LayerCanvas : Canvas
{
    private static readonly DependencyPropertyKey ReadOnlyCursorLocationPropertyKey =
        DependencyProperty.RegisterReadOnly("CursorLocation", typeof(Point), typeof(LayerCanvas),
        new PropertyMetadata(new Point(0, 0)));

    public static readonly DependencyProperty CursorLocationProperty =
        ReadOnlyCursorLocationPropertyKey.DependencyProperty;

    public LayerCanvas()
        : base()
    {

    }

    public Point CursorLocation
    {
        get { return (Point)GetValue(CursorLocationProperty); }
        private set { SetValue(ReadOnlyCursorLocationPropertyKey, value); }
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        base.OnMouseMove(e);
        this.CursorLocation = e.GetPosition(this);
    }
}

绑定到 View 的 XAML 中的属性为:

<local:LayerCanvas CursorLocation="{Binding Path=CursorLocation, Mode=OneWayToSource}" ... />

在 ViewModel 中将属性实现为:

public Point CursorLocation
{
    get { return this.cursorLocation; }
    set
    {
        this.cursorLocation = value;
        // ... logic ...
    }
}

我在 View 的 XAML 中收到错误 "CursorLocation cannot be data-bound." 和一个编译时错误 "The property 'LayerCanvas.CursorLocation' cannot be set because it does not have an accessible set accessor.",我认为 Mode=OneWayToSource 会修复它。我正在使用只读依赖属性而不是使用代码隐藏来尝试保持干净的 MVVM 实现。这是正确的方法吗?

【问题讨论】:

    标签: .net wpf data-binding dependency-properties


    【解决方案1】:

    来自MSDN

    由于不可设置,只读依赖属性 不适用于许多依赖项的场景 属性通常提供解决方案(即:数据绑定,直接 样式化为值、验证、动画、继承)。

    即使您将属性的设置器公开,数据绑定也不起作用。所以答案是否定的,这不是正确的方法。为了支持数据绑定,该属性不能是只读的,即使绑定仅是 OneWayToSource

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-19
      • 1970-01-01
      • 2010-12-17
      • 2021-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多