WPF:绑定到继承用户控件基础 class 的 class 的依赖项 属性

WPF: binding to dependency property of a class that inherits a user control base class

我在 wpf 中有一个名为 "GoogleMap.xaml/.cs" 的用户控件,其中 xaml 声明是这样开始的:

<controls:BaseUserControl x:Class="CompanyNamespace.Controls.GoogleMap"

背后的代码:

 public partial class GoogleMap : BaseUserControl{

        public static readonly DependencyProperty MapCenterProperty =
            DependencyProperty.Register("MapCenter", typeof(string), typeof(GoogleMap), new FrameworkPropertyMetadata(string.Empty, OnMapCenterPropertyChanged));

    public string MapCenter {
        get { return (string)GetValue(MapCenterProperty); }
        set { SetValue(MapCenterProperty, value); }
    } 

    private static void OnMapCenterPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e){
        GoogleMap control = source as GoogleMap;
        control.SetCenter(e.NewValue.ToString());
    }
...
}

我能够从 GoogleMap.xaml 解决 属性 的正确语法是什么:

MapCenter="{Binding Location}"

如果我将 属性 放在 BaseUserControl class 中,我只能从 GoogleMap.xaml 绑定到此 属性。

更新 GoogleMapViewModel.cs

public class GoogleMapViewModel : ContainerViewModel{


    private string location;
    [XmlAttribute("location")]
    public string Location {
        get {
            if (string.IsNullOrEmpty(location))
                return appContext.DeviceGeolocation.Location();

            return ExpressionEvaluator.Evaluate(location);
        }
        set {
            if (location == value)
                return;

            location = value;
            RaisePropertyChanged("Location");
        }
    }

为了将 UserControl 的 属性 绑定到它自己的 XAML 中,您可以声明一个样式:

<controls:BaseUserControl
    x:Class="CompanyNamespace.Controls.GoogleMap"
    xmlns:local="clr-namespace:CompanyNamespace.Controls"
    ...>
    <controls:BaseUserControl.Style>
        <Style>
            <Setter Property="local:GoogleMap.MapCenter" Value="{Binding Location}" />
        </Style>
    </controls:BaseUserControl.Style>
    ...
</controls:BaseUserControl>

如果 XML 命名空间 localcontrols 相同,那么它当然是多余的。


您也可以在 UserControl 的构造函数中创建绑定,例如:

public GoogleMap()
{
    InitializeComponent();
    SetBinding(MapCenterProperty, new Binding("Location"));
}