Xamarin.Forms 2.5.0 和上下文

问题描述 投票:0回答:3

今天我更新到 Xamarin.Forms 2.5.0 并看到,我收到以下警告:

  • 来自Android子项目:

    警告 CS0618 'Forms.Context' 已过时:'Context 自 2.5 版起已过时。请改用本地上下文。'

如何获取本地上下文而不是

Forms.Context
Android Context 是什么意思?

  • 来自自定义渲染器:

    警告 CS0618 'ButtonRenderer.ButtonRenderer()' 已过时:'此构造函数自版本 2.5 起已过时。请改用 ButtonRenderer(Context)。'

在我的

ButtonRenderer
中我只有
OnElementChanged()
方法,那么我应该在这里更改什么?简单地添加一个
ButtonRenderer(Context)
构造函数?如果我在平台渲染器类中执行此操作,我仍然会收到警告。有人有例子吗? 官方文档没有提及,Google也没有带来任何有用的结果,除了ButtonRenderer
开源代码。此更改还涉及许多其他渲染器类。

有人经历过其他变化吗,比如刹车插件等等?

PS:我也没有发现

Device.Windows
何时被弃用。现在我把它换成
Device.UWP

c# .net xamarin xamarin.forms custom-renderer
3个回答
33
投票

我对

SearchBarRenderer
也有同样的问题,我需要做的就是添加一个构造函数,如下所示:

public ShowSearchBarRenderer(Context context) : base(context)
{
}

希望能回答您问题的第二部分。


21
投票

这里有两个问题:

  1. 如何更新自定义渲染器以使用本地上下文?
  2. 既然
    Xamarin.Forms.Forms.Context
    已过时,我如何访问当前上下文?

如何更新自定义渲染器

将重载的构造函数添加到每个自定义渲染器

这是一个使用

ButtonRenderer

的示例
[assembly: ExportRenderer(typeof(CustomButton), typeof(CustomButtonRenderer))]
namespace MyApp.Droid
{
    public class CustomButtonRenderer : ButtonRenderer
    {
        public CustomButtonRenderer(Context context) : base(context)
        {

        }

        protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            //ToDo: Customize Button
        }
    }
}

如何访问当前上下文

安装Xamarin.Essentials NugGet 包

现在,当您需要访问当前活动时,可以调用

Xamarin.Essentials.Platform.AppContext

这是如何在 Xamarin.Forms 中打开应用程序设置的示例。

[assembly: Dependency(typeof(DeepLinks_Android))]
namespace MyApp.Droid
{
    public class DeepLinks_Android : IDeepLinks
    {
        Context CurrentContext => Xamarin.Essentials.Platform.AppContext;

        public Task OpenSettings()
        {
            var myAppSettingsIntent = new Intent(Settings.ActionApplicationDetailsSettings, Android.Net.Uri.Parse("package:" + CurrentContext.PackageName));
            myAppSettingsIntent.AddCategory(Intent.CategoryDefault);

            return Task.Run(() =>
            {
                try
                {
                    CurrentContext.StartActivity(myAppSettingsIntent);
                }
                catch (Exception)
                {
                    Toast.MakeText(CurrentContext.ApplicationContext, "Unable to open Settings", ToastLength.Short);
                }
            });
        }
    }
}

15
投票

使用

Android.App.Application.Context

论坛

上有关于此主题的讨论
© www.soinside.com 2019 - 2024. All rights reserved.