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

时间:2016-07-13 14:06:58

标签: c# wpf dependency-properties

我在wpf中有一个名为&#34的用户控件; 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类中,我只能从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");
        }
    }

1 个答案:

答案 0 :(得分:1)

为了将UserControl的属性绑定在自己的XAML中,您可以声明一个Style:

<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的构造函数中创建Binding,如:

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