I have added a button from xaml file like that:
<ContentView.Content>
<Button Image="{Binding Icon}" Text="{Binding Title}" Clicked="ClickEvent" HeightRequest="10" WidthRequest="10" />
</ContentView.Content>
How can I style the button to look like this?
I have css file in my xamarin project but I dont seem to reach Button image with it sucessfully because such code gives no result:
.button img {
height: 50px;
width: 50px;
}
My current result of a button (terrible), picture is way to big:
To be able to fully customize a button like that, it's probably best to implement your own Button control instead of using CSS:
XAML
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="YourApp.Views.SomeRoundImageButton">
<Frame
CornerRadius="8">
<Grid
RowDefinitions="2*,*">
<Image
Grid.Row="0"
Source="{Binding Icon}"/>
<Label
Grid.Row="1"
TextColor="Blue"
Text="{Binding Title}"/>
</Grid>
<Frame.GestureRecognizers>
<TapGestureRecognizer
Tapped="OnButtonTapped"/>
</Frame.GestureRecognizers>
</Frame>
</ContentView>
Code-behind
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace YourApp.Views {
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SomeRoundImageButton : ContentView {
public string Title {
get => (string)GetValue(TitleProperty);
set => SetValue(TitleProperty, value);
}
public ImageSource Icon {
get => (ImageSource)GetValue(IconProperty);
set => SetValue(IconProperty, value);
}
public event EventHandler<EventArgs> ButtonTapped;
public static readonly BindableProperty TitleProperty = BindableProperty.Create(nameof(Title), typeof(string), typeof(SomeRoundImageButton));
public static readonly BindableProperty IconProperty = BindableProperty.Create(nameof(Icon), typeof(ImageSource), typeof(SomeRoundImageButton));
public SomeRoundImageButton() {
InitializeComponent();
BindingContext = this;
}
private void OnButtonTapped(object sender, EventArgs e) {
ButtonTapped?.Invoke(this, e);
}
}
}
Usage
<ContentView.Content>
<StackLayout>
<views:SomeRoundImageButton
Icon="{Binding Icon}"
Title="{Binding Title}"
WidthRequest="80"
HeightRequest="80"
ButtonTapped="Clicked"/>
</StackLayout>
</ContentView.Content>
This gives you a lot more freedom for your design, you can make the Image bigger or smaller, add more lines of text to the Label, define the size of the CornerRadius
, set all kinds of other properties...
Obviously, you need to play around with it to figure out the intended design, but I hope this will be of help. Note, this is just one way of doing this. In Xamarin.Forms (and .NET MAUI), there are many ways of achieving the same things.