将字符串/方法形式MainPage传递给MainActivity Xamarin

时间:2016-11-28 15:30:31

标签: c# xaml xamarin

我想在MainActivity中使用MainPage中的varbele或方法。我已经为我的DependencyService创建了一个接口,但我总是在

处遇到同样的错误
 DependencyService.Get<IHPost>.HPost("R");

方法在给定的上下文中无效

我按照官方文档,所以我在PCL中创建了我的界面:

IHPost(公共界面)

在Xamarin.Android中,我已经编写了HPost_droid实现 [assembly:Dependency(typeof(HPost_droid))] line

在MainActivity中我添加了这个界面。

代码:

IHPost.cs(接口)

    namespace Xam
{
    public interface IHPost
    {
        void HPost(string val);
    }
}

MainPage.xaml.cs中

 public partial class MainPage : ContentPage
        {
            public MainPage()
            {
                InitializeComponent();
               // DependencyService.Get<IHPost>.HPost("R");
            }
        }

HPost_droid(Class)

[assembly: Dependency(typeof(HPost_droid))]
namespace Xam.Droid
{
    class HPost_droid : Java.Lang.Object, IHPost
    {
        public HPost_droid() { }

        public void HPost(string val)
        {
            System.Diagnostics.Debug.Write(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + val);
        }
    }
}

MainActivity

[assembly: Xamarin.Forms.Dependency(typeof(IHPost))]

namespace Xam.Droid
{
    [Activity(Label = "Xam", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : Xamarin.Forms.Platform.Android.FormsAppCompatActivity, IHPost
    {
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            DependencyService.Get<IHPost>.HPost("R");

            base.OnCreate(bundle);
            global::Xamarin.Forms.Forms.Init(this, bundle);
            LoadApplication(new App());
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我按照这个完美的教程从头开始重试:https://wolfprogrammer.com/2016/08/05/dependency-services-with-xamarin-forms/ 它的工作!