如何使用界面使MainPage.xaml.cs与MainActivity.cs对话

时间:2018-09-11 04:19:52

标签: c# xamarin xamarin.forms

我正在尝试让这些类共享一些数据,我读到正确的方法是通过接口,但是MainPage.xaml.cs无法识别“链接”。我需要在MainPage.xaml.cs中添加什么才能使其正常工作?

Class1.cs:

namespace interfaceWebnav
{
    public interface IPortableInterface
    {
        object Test();
    }
}

MediaService.cs

using interfaceWebnav;

namespace ComprarMusicas
{
    public class MediaService : Java.Lang.Object, IPortableInterface
    {
        public object Test()
        {
            //do something
        }
    }
}

MainActivity.cs:

...
...
using interfaceWebnav;

[assembly: Dependency(typeof(IPortableInterface))]
namespace MyApp.Droid
{
     [Activity(Label = "Comprar Músicas", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, NoHistory = true,ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity :  global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            ............
            base.OnCreate(savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }
   }

    public override void OnBackPressed()
    {
        // here I need to know what SomeMethod() from MainPage.xaml.cs is saying
    }

}

MainPage.xaml.cs(我注释掉了一些使其起作用的尝试):

using Xamarin.Forms;
// using interfaceWebnav;

// [assembly: Dependency(typeof(IPortableInterface))]

namespace MyApp
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
    }

    void SomeMethod(object sender, EventArgs e)
    {
        object resultado = DependencyService.Get<IPortableInterface>().Test();
    }
}

Visual Studio在MainPage.xaml.cs上说到SomeMethod:  “名称空间不能直接包含成员作为字段或方法。”

关于“获取IPortableInterface”,它说:

“找不到类型或名称空间IPortableInterface的名称(您是否缺少using指令或程序集引用?)”

1 个答案:

答案 0 :(得分:3)

添加类说您的android项目中的MediaService.cs是从IPortableInterface继承的

public class MediaService : Java.Lang.Object, IPortableInterface
{
    public void Test()
    {
        // your android platform specific implementation
    }

}

在MainPage.cs文件中,您的调用依赖项服务

namespace MyApp
{
    public partial class MainPage : ContentPage
    {
        public bool foo = true; //just an example

        public MainPage()
        {
            InitializeComponent();
        }
    }
    //I suppose invoking any event lets says button click calling interface dependency service of android project
    void Button_Clicked(object sender,EventArgs e)
    {
        object resultado = DependencyService.Get<IPortableInterface>().Test();
    }

}

希望这对您有帮助