Material Xamarin.Form 元素中的主题

Material Theme in Xamarin.Form element

在我的应用程序中,使用 Xamarin.Forms 按钮中的 steps here. I want to apply RaisedButton 颜色创建的 AppCompat 主题运行良好。为此,我尝试了以下操作:

但是它不起作用。由于这两个文件(MyView.xaml 和 style.xml)在不同的项目中。如何在 Xamarin.Forms 中添加 Widget.AppCompat.Button.Colored 样式的按钮?

您可以通过将自定义 ButtonRenderer 添加到您的 Xamarin.Android 项目来执行此操作:

new Button {
    WidthRequest = 50,
    Text = "Button"
},
new RaisedButton {
    WidthRequest = 50,
    Text = "RaisedButton"
}

layout/raisedbutton.axml(根据您的喜好自定义)

注意:Link 如果需要,将其添加到 style id 并编辑您的 style.xml

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/raisedbutton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Whosebug"
    android:textAllCaps="false"
    style="@style/Base.Widget.AppCompat.Button.Colored"
    android:gravity="center" />

RaisedButton.cs(在 PCL 项目中):


using Xamarin.Forms;

namespace MaterialDesignButton
{
    public class RaisedButton : Button
    {
    }
}

RaisedButtonRender.cs(在 Android 项目中)


using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using MaterialDesignButton;
using MaterialDesignButton.Droid;

[assembly: ExportRenderer(typeof(RaisedButton), typeof(RaisedButtonRender))]
namespace MaterialDesignButton.Droid
{
    public class RaisedButtonRender : ButtonRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
        {
            if (Control == null)
            {
                var raisedButton = (Android.Widget.Button)Inflate(Context, Resource.Layout.raisedbutton, null);

                //Additional code: To make it generic               
                if (e.NewElement != null)
                {
                    raisedButton.Text = e.NewElement.Text;
                    raisedButton.Click += (s, ar) =>
                    {
                        if (e.NewElement.Command.CanExecute(null))
                        {
                            e.NewElement.Command.Execute(null);
                        }
                    };
                }

                SetNativeControl(raisedButton);
            }
            base.OnElementChanged(e);
        }
    }
}

参考:https://developer.xamarin.com/guides/xamarin-forms/custom-renderer/