简体   繁体   中英

Xamarin.Forms, cannot reach class from platform specific projects

At first I have a Multi-platform Project where I created a Class which transfers Data and my problem is that as example if I click a Button a method in this class should be called but I cannot reach the method.

This is my project structure: 在此处输入图片说明

The red part is where the Data Handler is located the green part from where I get the clicked event and call the method.

I'll hope someone can help me with this problem!

As Jason mentioned in comment, you can not reach code from platform specific just like that , because you are not referencing platform specific projects, and there is something called DependencyService (which Jason also mentioned) and that will help you to solve this "issue" that you have.

This is how you can use DependencyService , inside your shared code project, create one interface in my case that will be:

public interface IDataHandler
{
    string GetSomeStringValue();
}

Go to your iOS or other platform specific project and create new class DataHandler.cs (which you already have). And it should implement this interface that we created. Something like this:

[assembly: Dependency(typeof(DataHandler))]
namespace provisioning.ios
{
    public class DataHandler: IDataHandler
    {

        public DataHandler()
        {
        }

        public string GetSomeStringValue()
        {
            return "Some string value or whatever";
        }
    }
}

After that when you want to reach this method you will use DepedencyService inside of your shared code project like this:

private void SomeMethod()
{
    string fromSpecificProject = DependencyService.Get<IDataHandler>().GetSomeStringValue();
}

If you want or need you can use this to pass some values to platform specific project and to return the data like I did it this mini example.

Note that implementations must be provided for each platform project in your solution. Platform projects without implementations will fail at runtime!

Strongly recommend you to take a look at official docs here .

Also I made this mini blogpost about usage of Dependency Service in Xamarin.Forms apps you can find it here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM