我一直努力遵循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