I'm trying to place a rounded Button in my Xamarin.Forms application, but I can't do it.
I read something about a custom controller to the button, but I didn't find any docs about rounded buttons in Xamarin.Forms.
Does anyone know how to do it? I'm just building an Android and iOS application.
You can use the BorderRadius property to create rounded corners on a Button
<Button Text="BlueButton"
BorderColor="Blue"
BorderRadius="5"
BorderWidth="2"/>
You need to use CornerRadius instead of BorderRadius because:
'Button.BorderRadius' is obsolete: 'BorderRadius is obsolete as of
2.5.0. Please use CornerRadius instead.'
Example: XButton.CornerRadius = 5;
If you are trying to have a Round button, use the below code. The height and width needs to be same and also proportionate to Border Radius.
<Button HorizontalOptions="Fill" VerticalOptions="Fill" Text="+">
<Button.WidthRequest>
<OnIdiom x:TypeArguments="x:Double" Phone="60" Tablet="80" />
</Button.WidthRequest>
<Button.HeightRequest>
<OnIdiom x:TypeArguments="x:Double" Phone="60" Tablet="80" />
</Button.HeightRequest>
<Button.BorderRadius>
<OnIdiom x:TypeArguments="x:Int32" Phone="30" Tablet="40" />
</Button.BorderRadius>
</Button>
You can ignore the different size for tablets if you are fine in having the same size on phone and tablets.
Note : This won't work on Windows. You will get a square button.
In Android, if your mainactivity is inheriting from AppCompact you will have to add this too.
The side of xaml the property is ConerRadius, Example:
<Button
CornerRadius="20"
Text="{i18n:Translate Cancel}"
Command="{Binding CancelarCommand}"
BackgroundColor="{StaticResource ButtonBackgroundColorbuscar}"
TextColor="White" />
If you want an image button you can use this ButtonCirclePlugin for Xamarin Forms.
Or an ImageCircle such as this ImageCirclePlugin for Xamarin Forms and add a TapGestureRecognizer.
There is no BorderRadius Property in the current version of Xamarin Forms. An alternative is the CornerRadius Property.
example:
<Button Text="Submit"
FontSize="Large"
TextColor="White"
BackgroundColor="Green"
CornerRadius="100"
To create rounded (circular) button try this...
<Button WidthRequest = 100,
HeightRequest = 100,
BorderRadius = 50 />
In general, WidthRequest=x, HeightRequest=x, BorderRadius=x/2
If you do not wish to drop down to using a renderer, and you don't mind not having a circular button on Windows Phone, you can use this code:
private const int BUTTON_BORDER_WIDTH = 1;
// Normal button height
//private const int BUTTON_HEIGHT = 44;
//private const int BUTTON_HEIGHT_WP = 72;
//private const int BUTTON_HALF_HEIGHT = 22;
//private const int BUTTON_HALF_HEIGHT_WP = 36;
//private const int BUTTON_WIDTH = 44;
//private const int BUTTON_WIDTH_WP = 72;
// Large button Height
private const int BUTTON_HEIGHT = 88;
private const int BUTTON_HEIGHT_WP = 144;
private const int BUTTON_HALF_HEIGHT = 44;
private const int BUTTON_HALF_HEIGHT_WP = 72;
private const int BUTTON_WIDTH = 88;
private const int BUTTON_WIDTH_WP = 144;
public RoundButtonPage()
{
var button = new Button
{
HorizontalOptions = LayoutOptions.Center,
BackgroundColor = Color.Accent,
BorderColor = Color.Black,
TextColor = Color.White,
BorderWidth = BUTTON_BORDER_WIDTH,
BorderRadius = Device.OnPlatform(BUTTON_HALF_HEIGHT, BUTTON_HALF_HEIGHT, BUTTON_HALF_HEIGHT_WP),
HeightRequest = Device.OnPlatform(BUTTON_HEIGHT, BUTTON_HEIGHT, BUTTON_HEIGHT_WP),
MinimumHeightRequest = Device.OnPlatform(BUTTON_HEIGHT, BUTTON_HEIGHT, BUTTON_HEIGHT_WP),
WidthRequest = Device.OnPlatform(BUTTON_WIDTH, BUTTON_WIDTH, BUTTON_WIDTH_WP),
MinimumWidthRequest = Device.OnPlatform(BUTTON_WIDTH, BUTTON_WIDTH, BUTTON_WIDTH_WP),
Text = "ClickMe"
};
var stack = new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Orientation = StackOrientation.Vertical,
Children = { button },
};
Padding = new Thickness(10, Device.OnPlatform(20, 0, 0), 10, 5);
Content = stack;
}
It will make a button with rounded corners. To make a button totally round you just set the border radius to be half of the height.
The only thing to remember is that your button has to be large enough to contain the contents. You can see what I mean by commenting/uncommenting out the two constant sections at the top. The first set is good for a number or letter, and the second one is good for a phrase, like "ClickMe."
Again, this uses the native buttons of the platform and since WP doesn't support a border radius all buttons on WP will be rectangular so you'll need to use the technique that James shows in the CircularImage control.
Try this C# code
private const int BUTTON_BORDER_WIDTH = 1;
private const int BUTTON_HEIGHT = 65;
private const int BUTTON_HEIGHT_WP = 40;
private const int BUTTON_HALF_HEIGHT = 33;
private const int BUTTON_HALF_HEIGHT_WP = 20;
private const int BUTTON_WIDTH = 65;
private const int BUTTON_WIDTH_WP = 20;
var chkIm = new Button()
{
BackgroundColor = Color.Black,
HorizontalOptions = LayoutOptions.Center,
TextColor = Color.White,
BorderRadius = Device.OnPlatform(BUTTON_HALF_HEIGHT, BUTTON_HALF_HEIGHT, BUTTON_HALF_HEIGHT_WP),
HeightRequest = Device.OnPlatform(BUTTON_HEIGHT, BUTTON_HEIGHT, BUTTON_HEIGHT_WP),
MinimumHeightRequest = Device.OnPlatform(BUTTON_HEIGHT, BUTTON_HEIGHT, BUTTON_HEIGHT_WP),
WidthRequest = Device.OnPlatform(BUTTON_WIDTH, BUTTON_WIDTH, BUTTON_WIDTH_WP),
MinimumWidthRequest = Device.OnPlatform(BUTTON_WIDTH, BUTTON_WIDTH, BUTTON_WIDTH_WP),
};
Yo can use this style and converter to get General Circular Button.
Style in App.xaml
<Style x:Key="CircleButton" TargetType="{x:Type Button}">
<Setter Property="CornerRadius" Value="{Binding Source={RelativeSource Self}, Path=WidthRequest, Converter={StaticResource NumberDivideConverter}, ConverterParameter=2}" />
<Setter Property="HeightRequest" Value="{Binding Source={RelativeSource Self}, Path=WidthRequest}" />
</Style>
Don't forget to add below line to your head of App.xaml:
xmlns:converters="clr-namespace:AlarteInclinometer.Converters"
and
<converters:NumberDivideConverter x:Key="NumberDivideConverter" />
to in App.xaml
Your converter class which divides corner radius to WidthRequest / 2 is:
NumberDivideConverter.cs:
public class NumberDivideConverter : IValueConverter
{
/// <summary>
/// Converts binding property to calculated new property
/// </summary>
/// <param name="value">Source value</param>
/// <param name="targetType">Target type of to be calculated (return) value.</param>
/// <param name="parameter">Converter parameter.</param>
/// <param name="culture">Converter culture.</param>
/// <returns>New calculated value.</returns>
/// <exception cref="ArgumentNullException">If value is null, throws ArgumentNullException</exception>
/// <exception cref="ArgumentException">If value cannot be converted to a integer, throws ArgumentException</exception>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// Check is value not null
if (value == null)
throw new ArgumentNullException($"Value is null");
// Check is value integer
if (int.TryParse(value.ToString(), out int intValue))
{
// If there is no parameter value, return same value
if (parameter == null)
return intValue;
// If there is converter parameter, divide number with it and return new result
if (int.TryParse(parameter.ToString(), out int param))
return intValue / param;
}
// Throw an error if value is not an integer
else
{
throw new ArgumentException($"The value must be a integer but it is a/an {value}");
}
return 0;
}
/// <summary>
/// Converts calculated property to binding property
/// </summary>
/// <param name="value">Source value</param>
/// <param name="targetType">Target type of to be calculated (return) value.</param>
/// <param name="parameter">Converter parameter.</param>
/// <param name="culture">Converter culture.</param>
/// <returns>New calculated value.</returns>
/// <exception cref="ArgumentNullException">If value is null, throws ArgumentNullException</exception>
/// <exception cref="ArgumentException">If value cannot be converted to a integer, throws ArgumentException</exception>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// Check is value not null
if (value == null)
throw new ArgumentNullException($"Value is null");
// Check is value integer
if (int.TryParse(value.ToString(), out int intValue))
{
// If there is no parameter value, return same value
if (parameter == null)
return intValue;
// If there is converter parameter, divide number with it and return new result
if (int.TryParse(parameter.ToString(), out int param))
return intValue * param;
}
// Throw an error if value is not an integer
else
{
throw new ArgumentException($"The target must be a integer but it is a/an {value}");
}
return 0;
}
}
After that, you can use this style in buttons where you want like:
<Button Text="Circular" WidthRequest="120" Style="{StaticResource CircleButton}" />
This is the best solution I think :)
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 9 months ago.
Improve this question
I have been stuck with an issue with regards to pinch and pan just on the Android platform but works well with iOS. I got my code for pinch and pan from here: Xamarin Forms pinch and pan together.
I have a carousel view that has multiple images and when I try to pinch and zoom the image on Android, no event for pinch updated is fired but it works well on iOS.
You could try the code below.
Xaml:
<ContentPage.Content>
<CarouselView ItemsSource="{Binding Images}">
<CarouselView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Frame HasShadow="True"
BorderColor="DarkGray"
CornerRadius="5"
Margin="20"
HeightRequest="300"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand">
<StackLayout>
<Label Text="{Binding Name}"
FontAttributes="Bold"
FontSize="Large"
HorizontalOptions="Center"
VerticalOptions="Center" />
<local:PinchToZoomContainer>
<local:PinchToZoomContainer.Content>
<Image Source="{Binding ImageUrl}"
Aspect="AspectFill"
HeightRequest="250"
WidthRequest="250"
HorizontalOptions="Center">
</Image>
</local:PinchToZoomContainer.Content>
</local:PinchToZoomContainer>
</StackLayout>
</Frame>
</StackLayout>
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
</ContentPage.Content>
Code behind:
public partial class Page27 : ContentPage
{
public Page27()
{
InitializeComponent();
this.BindingContext = new Page27ViewModel();
}
}
public class Page27Model
{
public string Name { get; set; }
public string ImageUrl { get; set; }
}
public class Page27ViewModel
{
public ObservableCollection<Page27Model> Images { get; set; }
public Page27ViewModel()
{
Images = new ObservableCollection<Page27Model>()
{
new Page27Model(){ Name="1", ImageUrl="durian.png" },
new Page27Model(){ Name="2", ImageUrl="durian.png" },
new Page27Model(){ Name="3", ImageUrl="durian.png" },
new Page27Model(){ Name="4", ImageUrl="durian.png" },
};
}
}
public class PinchToZoomContainer : ContentView
{
double currentScale = 1;
double startScale = 1;
double xOffset = 0;
double yOffset = 0;
public PinchToZoomContainer()
{
var pinchGesture = new PinchGestureRecognizer();
pinchGesture.PinchUpdated += OnPinchUpdated;
GestureRecognizers.Add(pinchGesture);
}
void OnPinchUpdated(object sender, PinchGestureUpdatedEventArgs e)
{
if (e.Status == GestureStatus.Started)
{
// Store the current scale factor applied to the wrapped user interface element,
// and zero the components for the center point of the translate transform.
startScale = Content.Scale;
Content.AnchorX = 0;
Content.AnchorY = 0;
}
if (e.Status == GestureStatus.Running)
{
// Calculate the scale factor to be applied.
currentScale += (e.Scale - 1) * startScale;
currentScale = Math.Max(1, currentScale);
// The ScaleOrigin is in relative coordinates to the wrapped user interface element,
// so get the X pixel coordinate.
double renderedX = Content.X + xOffset;
double deltaX = renderedX / Width;
double deltaWidth = Width / (Content.Width * startScale);
double originX = (e.ScaleOrigin.X - deltaX) * deltaWidth;
// The ScaleOrigin is in relative coordinates to the wrapped user interface element,
// so get the Y pixel coordinate.
double renderedY = Content.Y + yOffset;
double deltaY = renderedY / Height;
double deltaHeight = Height / (Content.Height * startScale);
double originY = (e.ScaleOrigin.Y - deltaY) * deltaHeight;
// Calculate the transformed element pixel coordinates.
double targetX = xOffset - (originX * Content.Width) * (currentScale - startScale);
double targetY = yOffset - (originY * Content.Height) * (currentScale - startScale);
// Apply translation based on the change in origin.
Content.TranslationX = targetX.Clamp(-Content.Width * (currentScale - 1), 0);
Content.TranslationY = targetY.Clamp(-Content.Height * (currentScale - 1), 0);
// Apply scale factor
Content.Scale = currentScale;
}
if (e.Status == GestureStatus.Completed)
{
// Store the translation delta's of the wrapped user interface element.
xOffset = Content.TranslationX;
yOffset = Content.TranslationY;
}
}
}
public static class DoubleExtensions
{
public static double Clamp(this double self, double min, double max)
{
return Math.Min(max, Math.Max(self, min));
}
}
I am manually positioning labels in an AbsoluteLayout.
To do this correctly I would like to know the label height prior to placing it on the UI.
I have found this solution, but not without actually placing a label:
public double MeasureLabelHeight(string text, double width, double fontSize, double lineHeight, string fontFamily)
{
Label label = new Label();
label.WidthRequest = width;
label.FontSize = fontSize;
label.LineHeight = lineHeight;
label.FontFamily = fontFamily;
label.LineBreakMode = LineBreakMode.WordWrap;
label.Text = text;
MyAbsoluteLayout.Children.Add(view: label, position: new Point(0, Height)); //place out of sight
var sizeRequest = label.Measure(widthConstraint: width, heightConstraint: double.MaxValue, flags: MeasureFlags.None);
var labelTextHeight = sizeRequest.Request.Height;
MyAbsoluteLayout.Children.Remove(label);
return labelTextHeight;
}
This solution works on UWP, I still have to test it on Android and iOS.
I would like to improve on it though.
I am unable to get a correct Height value without actually placing it in the AbsoluteLayout (out of view) and am a bit worried about the overhead this probably causes with extra redraws.
I have found an old piece of code that seemingly uses native code to do this without actually placing it in the UI for iOS and Android. I'm wondering if there is a solution available that has no need for platform specific code.
Let Xamarin Forms measure them for you. Then you move them into position.
Do this by subclassing AbsoluteLayout, and adding an Action that a page can set, to be called when your layout has done LayoutChildren.
MyAbsoluteLayout.cs:
using System;
using Xamarin.Forms;
namespace XFSOAnswers
{
public class MyAbsoluteLayout : AbsoluteLayout
{
public MyAbsoluteLayout()
{
}
// Containing page will set this, to act on children during LayoutChildren.
public Action CustomLayoutAction { get; set; }
private bool _busy;
protected override void LayoutChildren(double x, double y, double width, double height)
{
// Avoid recursed layout calls as CustomLayoutAction moves children.
if (_busy)
return;
// Xamarin measures the children.
base.LayoutChildren(x, y, width, height);
_busy = true;
try
{
CustomLayoutAction?.Invoke();
}
finally
{
_busy = false;
// Layout again, to position the children, based on adjusted (x,y)s.
base.LayoutChildren(x, y, width, height);
}
}
}
}
Example usage - MyAbsoluteLayoutPage.xaml:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:XFSOAnswers"
x:Class="XFSOAnswers.MyAbsoluteLayoutPage">
<ContentPage.Content>
<local:MyAbsoluteLayout x:Name="TheLayout">
<!-- Layout positions start (0,0). Adjusted later in PositionLabels. -->
<Label x:Name="Label1" Text="Welcome" />
<Label x:Name="Label2" Text="to" />
<Label x:Name="Label3" Text="Xamarin" />
<Label x:Name="Label4" Text=".Forms!" />
</local:MyAbsoluteLayout>
</ContentPage.Content>
</ContentPage>
MyAbsoluteLayoutPage.xaml.cs:
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace XFSOAnswers
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MyAbsoluteLayoutPage : ContentPage
{
public MyAbsoluteLayoutPage()
{
InitializeComponent();
TheLayout.CustomLayoutAction = PositionLabels;
}
private void PositionLabels()
{
// Optional: Set breakpoint after these, to check that the bounds have values.
var bounds1 = Label1.Bounds;
var bounds2 = Label2.Bounds;
var bounds3 = Label3.Bounds;
var bounds4 = Label4.Bounds;
double x = 10;
double y = 20;
MoveAbsoluteChildTo(Label1, x, y);
x += Label1.Width;
y += Label1.Height;
MoveAbsoluteChildTo(Label2, x, y);
x += Label2.Width;
y += Label2.Height;
MoveAbsoluteChildTo(Label3, x, y);
x += Label3.Width;
y += Label3.Height;
MoveAbsoluteChildTo(Label4, x, y);
}
private static void MoveAbsoluteChildTo(View child, double x, double y)
{
AbsoluteLayout.SetLayoutBounds(child, new Rect(x, y, child.Width, child.Height));
}
}
}
Result:
See MyAbsoluteLayout and MyAbsoluteLayoutPage in ToolmakerSteve - repo XFormsSOAnswers.
I copied/wrote a class that inherits from Frame
public class Circle : Frame
{
//private double _radius;
public static readonly BindableProperty RadiusProperty = BindableProperty.Create(nameof(Radius), typeof(double), typeof(Circle), 126.0, BindingMode.TwoWay);
public double Radius
{
get => (double)GetValue(RadiusProperty); //_radius;
set
{
SetValue(RadiusProperty, value);
OnPropertyChanged();
AdjustSize();
}
}
private void AdjustSize()
{
HeightRequest = Radius;
WidthRequest = Radius;
Margin = new Thickness(0,0,0,0);
Padding = new Thickness(0, 0, 0, 0);
CornerRadius = (float) (Radius / 2);
}
public Circle()
{
HorizontalOptions = LayoutOptions.Center;
}
}
The consuming page defines these BinadableProperties
public static readonly BindableProperty InnerColorProperty = BindableProperty.Create("InnerColor", typeof(Color), typeof(CircleProgressView), defaultValue: Color.FromHex("#34495E"), BindingMode.TwoWay);
public Color InnerColor
{
get => (Color)GetValue(InnerColorProperty);
set => SetValue(InnerColorProperty, value);
}
public static readonly BindableProperty InnerRadiusProperty = BindableProperty.Create("InnerRadius", typeof(double), typeof(CircleProgressView), 126.0, BindingMode.TwoWay);
public double InnerRadius
{
get => (double)GetValue(InnerRadiusProperty);
set => SetValue(InnerRadiusProperty, value);
}
And uses the Circle like so
<components:Circle Grid.Row="0" BackgroundColor="{Binding InnerColor}" Radius="{Binding InnerRadius}" >
Alas, the bindable's setter, and hence AdjustSize(), is never called nor is the default value used. Instead of a circle I end up with a rectangle. The BackgroundColor, which is a property of Frame, binds and works fine.
If I remove the BindableProperty and leave behind a regular INotify property
public class Circle : Frame
{
private double _radius;
public double Radius
{
get => _radius;
set
{
_radius = value;
OnPropertyChanged();
AdjustSize();
}
}
private void AdjustSize()
{
HeightRequest = Radius;
WidthRequest = Radius;
Margin = new Thickness(0,0,0,0);
Padding = new Thickness(0, 0, 0, 0);
CornerRadius = (float) (Radius / 2);
}
public Circle()
{
HorizontalOptions = LayoutOptions.Center;
}
}
The compiler complains if I keep the InnerRadius binding
Severity Code Description Project File Line Suppression State
Error Position 17:92. No property, bindable property, or event found for 'Radius', or mismatching type between value and property. ...\Components\CircleProgressView.xaml 17
I can replace the Radius binding with a hardcoded value and it runs fine, a circle appears.
<components:Circle Grid.Row="0" BackgroundColor="{Binding InnerColor}" Radius="126" >
What's wrong with a BindableProperty in a regular C# class?
Firstly, we need to handle data in the property changed event of bindable property instead of the setter method of a normal property. So modify your Circle class like:
public static readonly BindableProperty RadiusProperty = BindableProperty.Create(nameof(Radius), typeof(double), typeof(Circle), 125.0, BindingMode.TwoWay, propertyChanged: RadiusChanged);
public double Radius
{
get => (double)GetValue(RadiusProperty); //_radius;
set => SetValue(RadiusProperty, value);
}
static void RadiusChanged(BindableObject bindableObject, object oldValue, object newValue)
{
Circle circle = bindableObject as Circle;
circle.HeightRequest = (double)newValue;
circle.WidthRequest = (double)newValue;
circle.CornerRadius = (float)((double)newValue / 2);
}
This is because we bind data in XAML we should manipulate the bindable property's changed event directly.
Secondly, I saw you bound the property using the parent page's bindable property. Normally, we won't do that. We will consume a view model as the page's binding context and then bind the property to the binding context. However, if you do want to consume the parent page's bindable property as the Circle's binding context, try this way:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Sample.SecondPage"
xmlns:components="clr-namespace:Sample"
x:Name="Page">
<ContentPage.Content>
<StackLayout>
<components:Circle BackgroundColor="{Binding InnerColor, Source={x:Reference Page}}" Radius="{Binding InnerRadius, Source={x:Reference Page}}"/>
</StackLayout>
</ContentPage.Content>
</ContentPage>
Name your parent page first and change the circle's source to that.
Here, I used a different default Radius value comparing to InnerRadius so the property changed event will be called at the initial time.
I have implemented a progress ring with time using code referenced from display a timer using progressBar xamarin forms.
Now I want to bind the value of total time dynamically so that when the time reaches some fixed value, the progress ring starts progressing. How can I accomplish this?
Since ConverterParameter is not a bindable property, we can't use Binding. But we can try to customize this label with a bindable property and pass itself to the ConverterParameter.
Customize this label like:
public class MyLabel : Label
{
public double TotalTime
{
set { SetValue(TotalTimeProperty, value); }
get { return (double)GetValue(TotalTimeProperty); }
}
public static readonly BindableProperty TotalTimeProperty = BindableProperty.Create(nameof(TotalTime), typeof(double), typeof(MyLabel), default(double));
}
Then we can pass itself in the XAML:
<local:MyLabel x:Name="MyLabel"
TotalTime="{Binding TotalTime}"
Text="{Binding Source={x:Reference progressBar}, Path=Progress, Converter={StaticResource countDownTime}, ConverterParameter={x:Reference MyLabel}"
HorizontalOptions ="Center"
FontSize="20"
FontFamily = "Helvetica Neue"
TextColor = "Red" />
At last modify this TotalTime in the code behind:
public class BindModel : INotifyPropertyChanged
{
double totalTime;
public double TotalTime
{
set
{
totalTime = value;
onPropertyChanged("TotalTime");
}
get
{
return totalTime;
}
}
public event PropertyChangedEventHandler PropertyChanged;
void onPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
// And set this model as a BindingContext
var model = new BindModel { TotalTime = 60000 };
BindingContext = model;
Also your IValueConverter should be like this:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double time = 0;
double myTotalTime = ((MyLabel)parameter).TotalTime;
double.TryParse(myTotalTime.ToString(), out var totalTime);
double.TryParse(value.ToString(), out var progress);
time = progress <= double.Epsilon ? totalTime : (totalTime - (totalTime * progress));
var timeSpan = TimeSpan.FromMilliseconds(time);
return $"{timeSpan.Minutes:00;00}:{timeSpan.Seconds:00;00}";
}
theres is a way to set a multi-line text to a Xamarin.Forms Button??
I've tried Button.Text = "something \n xxjjjxx" But don't work.
A simple solution will use:
There is an excellent example on how to achieve this on Github. It is quite simple really. Just create your own control that inherits from ContentView and contains a grid.
[ContentProperty("Content")]
public class MultiLineButton : ContentView
{
public event EventHandler Clicked;
protected Grid ContentGrid;
protected ContentView ContentContainer;
protected Label TextContainer;
public String Text
{
get
{
return (String)GetValue(TextProperty);
}
set
{
SetValue(TextProperty, value);
OnPropertyChanged();
RaiseTextChanged();
}
}
public new View Content
{
get { return ContentContainer.Content; }
set
{
if (ContentGrid.Children.Contains(value))
return;
ContentContainer.Content = value;
}
}
public static BindableProperty TextProperty = BindableProperty.Create(
propertyName: "Text",
returnType: typeof(String),
declaringType: typeof(MultiLineButton),
defaultValue: null,
defaultBindingMode: BindingMode.TwoWay,
propertyChanged: TextValueChanged);
private static void TextValueChanged(BindableObject bindable, object oldValue, object newValue)
{
((MultiLineButton)bindable).TextContainer.Text = (String)newValue;
}
public event EventHandler TextChanged;
private void RaiseTextChanged()
{
if (TextChanged != null)
TextChanged(this, EventArgs.Empty);
}
public MultiLineButton()
{
ContentGrid = new Grid
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand
};
ContentGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
ContentGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
ContentContainer = new ContentView
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
};
TextContainer = new Label
{
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.FillAndExpand,
};
ContentContainer.Content = TextContainer;
ContentGrid.Children.Add(ContentContainer);
var button = new Button
{
VerticalOptions = LayoutOptions.FillAndExpand,
HorizontalOptions = LayoutOptions.FillAndExpand,
BackgroundColor = Color.FromHex("#01000000")
};
button.Clicked += (sender, e) => OnClicked();
ContentGrid.Children.Add(button);
base.Content = ContentGrid;
}
public void OnClicked()
{
if (Clicked != null)
Clicked(this, new EventArgs());
}
}
Then it can be used like this:
<local:MultiLineButton x:Name="AssessmentToolDetailButton"
WidthRequest="100" HeightRequest="60" BackgroundColor="Blue">
<StackLayout HorizontalOptions="Center" VerticalOptions="CenterAndExpand">
<Label Text="Hello" TextColor="White" Font="16"/>
<Label Text="World" TextColor="White" Font="16"/>
</StackLayout>
</local:MultiLineButton>
You can also place an image in the button by setting its content.
In my example I modified Dans original code in order to make the text bindable. Just set the Text value instead of the Content like this:
<local:MultiLineButton Text="{Binding Description}" />
All credit goes to Danvanderboom for his example:
ConentButton by Danvanderboom
This is mainly a problem with iOS because Android will wrap the text
by default. I tried the solution provided by Kasper and it worked
however the buttons do not have rounded corners and the appearance is
not consistent with other buttons in my app.
A simple solution is to use a custom renderer (ButtonRenderer) to set the LineBreakMode to WordWrap. If you then set the width of the button in the Xaml you get words to appear on different lines.
iOS
public class WrappedButtonRenderer: ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
Control.TitleEdgeInsets = new UIEdgeInsets(4, 4, 4, 4);
Control.TitleLabel.LineBreakMode = UILineBreakMode.WordWrap;
Control.TitleLabel.TextAlignment = UITextAlignment.Center;
}
}
Android does not require a custom renderer because it wraps by default.
This is a known issue with Xamarin Forms.
I don't think I've seen two lined buttons often. You have two options that I think might work:
Create a Custom Renderer and Extend the respective Button Class to do more on each native platform. Might be a harder
Create a Xamarin.Forms Class that extends a View that can contains a StackLayout and smaller elements such as multi-line labels, then you can use a TapGestureRecognizer to use with your view and treat it like a button.
Expanding on fireydude's answer, I created a MultilineButton control and renderer for iOS so I could add text alignment. This uses the Xamarin.Forms.TextAlignment enum.
MultilineButton.cs
using Xamarin.Forms;
namespace APP_NAMESPACE.Controls
{
public class MultilineButton : Button
{
public static readonly BindableProperty HorizontalTextAlignmentProperty = BindableProperty.Create(
propertyName: "HorizontalTextAlignment",
returnType: typeof(TextAlignment),
declaringType: typeof(MultilineButton),
defaultValue: TextAlignment.Start
);
public TextAlignment HorizontalTextAlignment
{
get { return (TextAlignment)GetValue(HorizontalTextAlignmentProperty); }
set { SetValue(HorizontalTextAlignmentProperty, value); }
}
}
}
MultilineButtonRenderer.cs
using APP_NAMESPACE.Controls;
using APP_NAMESPACE.iOS.Renderers;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(MultilineButton), typeof(MultilineButtonRenderer))]
namespace APP_NAMESPACE.iOS.Renderers
{
public class MultilineButtonRenderer : ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
if (Control == null) { return; }
UIControlContentHorizontalAlignment horizontalAlignment;
UITextAlignment textAlignment;
// We have to use ButtonRenderer, so cast the Element to MultilineButton to get the HorizontalTextAlignment property
var button = (MultilineButton)Element;
if (button == null) { return; }
switch(button.HorizontalTextAlignment)
{
case TextAlignment.Center:
horizontalAlignment = UIControlContentHorizontalAlignment.Center;
textAlignment = UITextAlignment.Center;
break;
case TextAlignment.End:
horizontalAlignment = UIControlContentHorizontalAlignment.Right;
textAlignment = UITextAlignment.Right;
break;
default:
horizontalAlignment = UIControlContentHorizontalAlignment.Left;
textAlignment = UITextAlignment.Left;
break;
}
Control.HorizontalAlignment = horizontalAlignment;
Control.TitleLabel.LineBreakMode = UILineBreakMode.WordWrap;
Control.TitleLabel.TextAlignment = textAlignment;
}
}
}
Then use it within XAML:
<controls:MultilineButton Text="This Button is Centered!" HorizontalTextAlignment="Center" />