使用View中的只读依赖项属性在ViewModel中设置属性

时间:2013-02-16 23:30:48

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

我一直在尝试关注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实现。这是正确的方法吗?

1 个答案:

答案 0 :(得分:4)

来自MSDN

  

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

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