简体   繁体   中英

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

I have a user control in wpf named "GoogleMap.xaml/.cs" where the xaml declaration starts like this:

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

the code behind:

 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());
    }
...
}

What's the correct syntax for me to be able to address the property from GoogleMap.xaml:

MapCenter="{Binding Location}"

I can only bind to this property from GoogleMap.xaml if I place the property is in the BaseUserControl class.

Update 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");
        }
    }

In order to bind a UserControl's property in its own XAML, you could declare a 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>

The XML namespace local is of course redundant if its identical to controls .


You could as well create the Binding in the UserControl's constructor like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM