Reputation: 2834
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");
}
}
Upvotes: 0
Views: 1136
Reputation: 128042
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"));
}
Upvotes: 1