【发布时间】: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