Reputation: 2187
In my application, the AppCompat Theme is working fine created using steps here. I want to apply RaisedButton color in Xamarin.Forms Button. For this I have tried following:
Added style in MyApplication.Droid > Resources > Values> style.xml
refering as:
<style name="MyRaisedButton" parent="Widget.AppCompat.Button.Colored"></style>
Added a button in MyApplication.Shared Portable form library in view MyView.xaml:
<Button Style="{StaticResource MyRaisedButton}" Text="Raised Button" />
But its not working. As these two files (MyView.xaml and style.xml) are in different projects. How can I add buttons in Xamarin.Forms with Widget.AppCompat.Button.Colored
style?
Upvotes: 3
Views: 1927
Reputation: 74124
You can do this with a custom ButtonRenderer
added to your Xamarin.Android
project:
new Button {
WidthRequest = 50,
Text = "Button"
},
new RaisedButton {
WidthRequest = 50,
Text = "RaisedButton"
}
layout/raisedbutton.axml
(customize to your liking)Note: Link it to a style
id if desired and edit your 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
(In PCL project):using Xamarin.Forms;
namespace MaterialDesignButton
{
public class RaisedButton : Button
{
}
}
RaisedButtonRender.cs
(In Android project)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);
}
}
}
Ref: https://developer.xamarin.com/guides/xamarin-forms/custom-renderer/
Upvotes: 4