我一直努力遵循a StackOverflow post以及官方documentation on MSDN实现在子类中的WPF画布的只读依赖属性控制由ViewModel使用。从视图设置的视图模型的属性有只读依赖属性
我定义我的子类帆布为:
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);
}
}
绑定到的属性中查看的XAML为:
<local:LayerCanvas CursorLocation="{Binding Path=CursorLocation, Mode=OneWayToSource}" ... />
实施中的视图模型属性为:
public Point CursorLocation
{
get { return this.cursorLocation; }
set
{
this.cursorLocation = value;
// ... logic ...
}
}
我在视图的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实现。这是正确的方法吗?
谢谢你的澄清。 – Noren 2013-02-18 15:47:16