我一直在尝试关注StackOverflow 帖子以及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."
的编译时错误。我正在使用只读依赖属性而不是使用代码隐藏来尝试保持干净的 MVVM 实现。这是正确的方法吗?"The property 'LayerCanvas.CursorLocation' cannot be set because it does not have an accessible set accessor."
Mode=OneWayToSource