在 UserControl 内部绑定

Binding inside UserControl

我创建了一个自定义用户控件。在 blog post 之后,我的控制代码隐藏如下所示:

public BasicGeoposition PinGeoposition
{
    get { return (BasicGeoposition) GetValue(PropertyPinGeoposition); }
    set { SetValueDp(PropertyPinGeoposition, value);}
}

public static readonly DependencyProperty PropertyPinGeoposition = 
    DependencyProperty.Register("PinGeoposition", typeof(BasicGeoposition), typeof(CustomMapControl), null);

public event PropertyChangedEventHandler PropertyChanged;
void SetValueDp(DependencyProperty property, object value, [System.Runtime.CompilerServices.CallerMemberName] String p = null)
{
    ViewModel.SetMode(ECustomMapControlMode.Default);
    SetValue(property, value);
    if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs(p));
}

使用我的控件:

<customControls:CustomMapControl Mode="ForImage" PinGeoposition="{Binding Geoposition, Mode=TwoWay}" Grid.Row="1"/>

最后,在我使用控件的页面的 ViewModel 中,我有:

public BasicGeoposition Geoposition
{
    get { return _geoposition; }
    set
    {
        if (Set(ref _geoposition, value))
        {
            RaisePropertyChanged(() => Geoposition);
        }
    }
}

我希望 ViewModel 中 Geoposition 的每一次变化都反映在 SetValueDp 中。不幸的是,它不起作用。

不确定 Jerry Nixon 在他的博客文章中试图做什么,因为他没有在任何地方分配他的 SetValueDp 方法。

如果你想让它被调用,你可以这样做:

public static readonly DependencyProperty PropertyPinGeoposition = 
DependencyProperty.Register("PinGeoposition", typeof(BasicGeoposition), typeof(CustomMapControl), new PropertyMetadata(null, SetPosition));

public BasicGeoposition PinGeoposition 
{ 
    get { return (BasicGeoposition) GetValue(PropertyPinGeoposition); } 
    set { SetValue(PropertyPinGeoposition, value);}
}

private static void SetPosition(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
    var control = (CustomMapControl)sender;

    var position = e.NewValue as BasicGeoposition;

    // Do whatever
}

编辑: 阅读并重新阅读博客文章后,我想我搞反了(您可能也是)。根据我现在的理解,SetValueDp 是一个辅助方法,只要您想更改依赖项 属性 的值,就应该调用它。这不是自动调用的东西。因此,如果您想要一个在修改 DP 时调用的方法,请改为查看我的解决方案。