0

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"); } } 
3
  • 1
    Since you are inheriting from the base class it shouldn't matter where you put the property. What does your DataContext look like? Commented Jul 13, 2016 at 14:11
  • I think it would be better to create a custom control and define its visual in a ControlTemplate. Commented Jul 13, 2016 at 14:28
  • added the vm there Commented Jul 13, 2016 at 14:50

1 Answer 1

1

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")); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.