If you want to define the Binding in XAML, I don't see another way to do so without defining an instance of your ViewModel under Resource.If your ViewModel object looked like this
public class MyViewModelObject : INotifyPropertyChanged
{
public MyViewModelObject()
{
Graphics = new GraphicCollection();
}
private GraphicCollection graphics;
public GraphicCollection Graphics
{
get { return graphics; }
set
{
if (graphics != value)
{
graphics = value;
OnPropertyChanged("Graphics");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
You might be expecting that when you set your UserControl's DataContext to an instance of your ViewModel in code-behind like this:
MyViewModelObject obj = new MyViewModelObject();
this.DataContext = obj;
the following XAML-code would just work:
<esri:GraphicsLayer ID="MyGraphicsLayer" Graphics="{Binding Graphics}">
Unfortunately, this is not the case. While your Map can inherit the DataContext of your UserControl, GraphicsLayer will not. GraphicsLayer, unlike Map or any other UIElement, does not have a DataContext and will therefore fail to resolve this type of Binding.If you wish to define the Binding in code-behind, these two are equivalent:XAML:
<Grid.Resources>
<local:MyViewModelObject x:Key="obj"/>
</Grid.Resources>
<!-- more code here -->
<esri:GraphicsLayer ID="MyGraphicsLayer" Graphics="{Binding Source={StaticResource obj}, Path=Graphics, Mode=TwoWay}" >
Code-behind:
MyViewModelObject obj = new MyViewModelObject();
GraphicsLayer layer = this.MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer;
System.Windows.Data.Binding binding = new System.Windows.Data.Binding("Graphics");
binding.Source = obj;
binding.Mode = System.Windows.Data.BindingMode.TwoWay;
System.Windows.Data.BindingOperations.SetBinding(layer, GraphicsLayer.GraphicsProperty, binding);
Either way will let you modify the elements in your Map's GraphicsLayer.
obj.Graphics.Add(new Graphic() { Geometry = new MapPoint(17, 15) });