Search code examples
c#.netxamlmaui

.Net MAUI FindResource Method


In .Net WPF, there is a method called FindResource() for getting binded source with its key. So I need it while developing my application in .Net MAUI. Unfortunately, there is no method called FindResource or anything like it. I searched about my problem but couldn't find any answer. I actually found a post about this problem on stackoverflow but I couldn't find my answer there.

Here is my code:

private void OnMapTapped(object sender, TappedEventArgs e)
{
    var viewModel = FindResource("MapViewModel") as MapViewModel;
    Point? p = e.GetPosition(MainMapView);
    Point pT = p.Value;
    MapPoint mp = MainMapView.ScreenToLocation(pT);
    viewModel.createPoint(mp);
}

The code that I used for declaring a resource.

<ContentPage.Resources>
    <local:MapViewModel x:Key="MapViewModel"/>
</ContentPage.Resources>

I'm currently trying to use ArcGIS maps in my application, and in this code I'm trying to put a marker on the tapped point. However, because the FindResource method is not avalible, I can't do it. I'm following ArcGIS tutorials and MVVM pattern is used there.

This is my first time posting a question on stackoverflow, so I apologize if I did something wrong.


Solution

  • I couldn't find any alternatives for FindResource() but with a small change I could get it to work without the need of FindResource().

    How I fixed the issue:

    This was the initial state of the code that I use for getting MapViewModel class in the .xaml file. My aim was to access this resource in the C# script file of the page with FindResource() method, but as I said before there was no method like it in .Net MAUI.

    <ContentPage.Resources>
        <local:MapViewModel x:Key="MapViewModel"/>
    </ContentPage.Resources>
    

    So I gave a name to this resource, with x:Name=" ". Here is the final state of the code

    <ContentPage.Resources>
        <local:MapViewModel x:Key="MapViewModel" x:Name="MVM"/>
    </ContentPage.Resources>
    

    So now I can access this resource in the C# script file of the page with the name I gave it, MVM.