简体   繁体   English

Xamarin.Forms,无法从特定于平台的项目中上课

[英]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. 红色部分是数据处理程序所在的位置,绿色部分是我获得clicked事件并调用该方法的位置。

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. 正如Jason在评论中提到的那样,您不能像这样从平台特定的地方访问代码,因为您没有引用平台特定的项目,并且有一个名为DependencyService东西(Jason也提到了),它将帮助您解决此“问题”你有。

This is how you can use DependencyService , inside your shared code project, create one interface in my case that will be: 这是您可以在共享代码项目内使用DependencyService ,在我的情况下,创建一个接口是:

public interface IDataHandler
{
    string GetSomeStringValue();
}

Go to your iOS or other platform specific project and create new class DataHandler.cs (which you already have). 转到您的iOS或其他特定于平台的项目,并创建新的类DataHandler.cs(您已经拥有)。 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: 之后,当您想使用此方法时,将在共享代码项目内部使用DepedencyService,如下所示:

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 . 我也做了一个关于Xamarin.Forms应用程序中Dependency Service用法的微型博客文章,您可以在这里找到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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