I'm using the recommended MVVM method to create an ArcGIS map in my WPF app and in my map initialisation SetupMap() I'm using a local webservice for the map resource, however the URL for the webservice is not known at the time the MapViewModel instance is created and hence the map initialisation function cannot create the map at that time. The URL for webservice is loaded later from an XML config file, so I need to call the SetupMap() function once that URL is known.
.xaml code is -
<Window.Resources>
<local:MapViewModel x:Key="MapViewModel" />
</Window.Resources>
and below in the grid -
<Grid>
<esri:MapView x:Name="MainMapView" Map="{Binding SiteBaseMap, Source={StaticResource MapViewModel}}" />
</Grid>
MapViewModel class -
public class MapViewModel : INotifyPropertyChanged
{
public MapViewModel()
{
SetupMap();
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private Map _map;
public Map SiteBaseMap
{
get { return _map; }
set { _map = value; OnPropertyChanged(); }
}
private void SetupMap()
{
// Create a new map with a 'topographic vector' basemap.
SiteBaseMap = new Map(BasemapStyle.ArcGISImageryStandard);
}
public void arcGISAddLayers(string iURI, string sURI)
{
Uri imageUri = new Uri(iURI);
Uri surfaceUri = new Uri(sURI);
// Create new tiled layer from the url
ArcGISTiledLayer imageLayer = new ArcGISTiledLayer(imageUri);
ArcGISTiledLayer surfaceLayer = new ArcGISTiledLayer(surfaceUri);
}
// add layers etc below here...
}
As per the previously answered question
Accessing a resource via codebehind in WPF
I have tried
object resource = Application.Current.TryFindResource("MapViewModel");
MapViewModel mvm = (MapViewModel)resource;
but mvm is null so it has not found the resource.
Am I assigning the resource incorrectly or why is it not finding the resource?
Update -
this does work -
object resource = this.Resources["MapViewModel"];
MapViewModel mvm = (MapViewModel)resource;
and so does this -
object resource = this.TryFindResource("MapViewModel");
MapViewModel mvm = (MapViewModel)resource;
but I would like to know why the first way doesn't (since this is one of the suggested solutions in the previously answered question).