Есть ли способ в Xamarin Forms изменить цвет фона диалогового окна? - PullRequest
0 голосов
/ 13 февраля 2020

Вот как выглядит мое диалоговое окно с темной темой.

enter image description here

Кто-нибудь знает, как можно изменить цвета в приложении Xamarin Forms, чтобы диалоговое окно отображалось с белым текстом на темном фоне? ?

Кто-нибудь знает, в чем может быть проблема?

1 Ответ

2 голосов
/ 14 февраля 2020

Вариант 1

Вы можете изменить его в определенных c платформах, используя DependencyService

в формах

создать интерфейс

using Xamarin.Forms;
namespace xxx
{
    public interface IPopUp
    {
        void Popup(string title, string message,Color titleColor,Color messageColor, EventHandler handler);
    }
}

в iOS

using System;


using System.Text;
using xxx.iOS;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using xxx;

[assembly: Dependency(typeof(PopupImplemention))]
namespace xxx.iOS
{
    public class PopupImplemention : IPopUp
    {
        public void Popup(string title, string message, Color titleColor, Color messageColor, EventHandler handler)
        {
            UIAlertController alertController = UIAlertController.Create(title,message,UIAlertControllerStyle.Alert);


            var firstAttributes = new UIStringAttributes
            {
                ForegroundColor =titleColor.ToUIColor(),

            };

            var secondAttributes = new UIStringAttributes
            {
                ForegroundColor =messageColor.ToUIColor(),

            };

            alertController.SetValueForKey(new NSAttributedString(title, firstAttributes), new NSString("attributedTitle"));
            alertController.SetValueForKey(new NSAttributedString(message, secondAttributes), new NSString("attributedMessage"));

            UIAlertAction cancelAction = UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,null);
            UIAlertAction okAction = UIAlertAction.Create("OK", UIAlertActionStyle.Default,(sender)=> { handler?.Invoke(sender, new EventArgs()) ; });

            alertController.AddAction(cancelAction);
            alertController.AddAction(okAction);

            var currentViewController = topViewControllerWithRootViewController(UIApplication.SharedApplication.Delegate.GetWindow().RootViewController);
            currentViewController.PresentViewController(alertController,true,null);
        }



        UIViewController topViewControllerWithRootViewController(UIViewController rootViewController)
        {
            if (rootViewController is UITabBarController)
            {
                UITabBarController tabBarController = (UITabBarController)rootViewController;
                return topViewControllerWithRootViewController(tabBarController.SelectedViewController);
            }
            else if (rootViewController is UINavigationController)
            {
                UINavigationController navigationController = (UINavigationController)rootViewController;
                return topViewControllerWithRootViewController(navigationController.VisibleViewController);
            }
            else if (rootViewController.PresentedViewController != null)
            {
                UIViewController presentedViewController = rootViewController.PresentedViewController;
                return topViewControllerWithRootViewController(presentedViewController);
            }
            else
            {
                return rootViewController;
            }
        }
    }
}

enter image description here

в Android

в MainActivity

public static MainActivity Intance;

protected override void OnCreate(Bundle savedInstanceState)
{
  TabLayoutResource = Resource.Layout.Tabbar;
  ToolbarResource = Resource.Layout.Toolbar;

  base.OnCreate(savedInstanceState);
  Intance = this;

  Xamarin.Essentials.Platform.Init(this, savedInstanceState);
  global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

  LoadApplication(new App());
}
using Xamarin.Forms;

using xxx;
using xxx.Droid;
using Android;
using System;
using Xamarin.Forms.Platform.Android;
using Android.Support.V7.App;
using Android.Text;

[assembly: Dependency(typeof(PopupImplemention))]
namespace xxx.Droid
{
    public class PopupImplemention : IPopUp
    {
        public void Popup(string title, string message, Color titleColor, Color messageColor, EventHandler handler)
        {

            // because html.string could not support format string , so you need to set the color directly in the string with a static value

            Android.Support.V7.App.AlertDialog.Builder alert = new Android.Support.V7.App.AlertDialog.Builder(MainActivity.Intance);
            alert.SetTitle(Html.FromHtml(string.Format("<font color='#ff0000'>{0}</font>" ,title),FromHtmlOptions.ModeLegacy));
            alert.SetMessage(Html.FromHtml(string.Format("<font color='#00ff00'>{0}</font>", message), FromHtmlOptions.ModeLegacy));

            alert.SetPositiveButton("OK", (senderAlert, args) =>
            {
                handler?.Invoke(senderAlert, args);
            });

            alert.SetNegativeButton("Cancel", (senderAlert, args) =>
            {

            });


            Android.Support.V7.App.AlertDialog dialog = alert.Create();
            dialog.Show();


        }
    }
}

и вызывать его в формах

 DependencyService.Get<IPopUp>().Popup("Title","xxxxxxxxxxxx",Color.Red,Color.Blue,(sen,args)=> { 

       // handle the logic when  clikc the OK button   

});

Option 2

Вы можете использовать плагин Rg.Plugins .Popup , который позволяет открывать страницы Xamarin.Forms в виде всплывающего окна, которое можно использовать для iOS, Android и UWP. И вы можете настроить его, как вы хотите.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...