在我的应用程序中,AppCompat主题使用steps here正常工作。我想在Xamarin.Forms按钮中应用RaisedButton颜色。为此,我尝试了以下内容:
在MyApplication.Droid > Resources > Values> style.xml
refering中添加了样式:
<style name="MyRaisedButton" parent="Widget.AppCompat.Button.Colored"></style>
在视图MyView.xaml中的MyApplication.Shared Portable表单库中添加了一个按钮:
<Button Style="{StaticResource MyRaisedButton}" Text="Raised Button" />
但它不起作用。由于这两个文件(MyView.xaml和style.xml)位于不同的项目中。如何在Widget.AppCompat.Button.Colored
样式的Xamarin.Forms中添加按钮?
答案 0 :(得分:3)
您可以使用添加到ButtonRenderer
项目的自定义Xamarin.Android
执行此操作:
new Button {
WidthRequest = 50,
Text = "Button"
},
new RaisedButton {
WidthRequest = 50,
Text = "RaisedButton"
}
layout/raisedbutton.axml
(根据自己的喜好自定义)注意:如果需要,请将其与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="StackOverflow"
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/