Xamarin.Forms 2.5.0和Context

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

  • 来自Android子项目:

    警告CS0618’Forms.Context’已废弃:’版本2.5已废弃上下文。 请改用当地语境。’

如何获取本地上下文而不是Forms.Context ? Android上下文意味着什么?

  • 从自定义渲染器:

    警告CS0618’ButtonRenderer.ButtonRenderer()’已废弃:’从2.5版开始,此构造函数已过时。 请改用ButtonRenderer(Context)。

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

有没有人经历过其他变化,制动插件等等?

PS:我也没有发现,当Device.Windows被弃用时。 现在我用Device.UWP替换它。

我对SearchBarRenderer也遇到了同样的问题,我需要做的就是修复它,就像这样添加一个构造函数:

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

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

使用Android.App.Application.Context

在论坛上讨论了这个主题

这里有两个问题:

  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 } } } 

如何访问当前上下文

安装@Motz的CurrentActivityPlugin 。

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

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

 [assembly: Dependency(typeof(DeepLinks_Android))] namespace MyApp.Droid { public class DeepLinks_Android : IDeepLinks { Context CurrentContext => CrossCurrentActivity.Current.Activity; 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); } }); } } }