2

I started using .NET MAUI recently and I found a problem with Styling. I started with the basic project to make sure the problem is not something I made during the process. The project starts with a button that will change text and size each time the user press it. enter image description here

The problem is any time I use LinearGradientBrush directly or through the global styling, the button size doesn't change to fit the text, and even worse it moves to the left. enter image description here

I looked everywhere but I didn't find any similar problem or solution.

It works well with Windows but not with Android

Code

<Button
                x:Name="CounterBtn"
                Text="Click me"
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnCounterClicked"
                HorizontalOptions="Center">
                <Button.Background>
                    <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
                        <GradientStop Color="#8A26ED"/>
                        <GradientStop Color="#381061" Offset="1"/>
                    </LinearGradientBrush>
                </Button.Background>
            </Button>
  • 1
    I confirm that this happens when I add the `...` xaml to standard template. Please create an issue at github maui issues. – ToolmakerSteve Nov 23 '22 at 18:06

2 Answers2

1

I can reproduce your issue and it's really weird. My workaround here is just set background again in Button click event handler:

private void OnCounterClicked(object sender, EventArgs e)
{
    LinearGradientBrush ll = new LinearGradientBrush();
    ll.EndPoint = new Point(0, 1);
    GradientStop a = new GradientStop(Color.FromHex("#8A26ED"), 0);
    GradientStop b = new GradientStop(Color.FromHex("#381061"), 1);
    ll.GradientStops = new GradientStopCollection()
    {
        a,b
    };
    CounterBtn.Background = ll;  
    ...
}

That works for me.

Liqun Shen-MSFT
  • 3,490
  • 2
  • 3
  • 11
0

Thanks to Liqun Shen-MSFT I figured out that the Button size does change however for some reason the button background doesn't rerender so it looks like it moves to the left but it's just the background color stick to the same area on the left leaving the rest of the button transparent.

I used the workaround but on SizeChanged event as it will be more accurate this way since the size of the button depends on the text/content length

 private void CounterBtn_SizeChanged(object sender, EventArgs e)
    {
        LinearGradientBrush ll = new LinearGradientBrush();
        ll.EndPoint = new Point(0, 1);
        GradientStop a = new GradientStop(Color.FromHex("#8A26ED"), 0);
        GradientStop b = new GradientStop(Color.FromHex("#381061"), 1);
        ll.GradientStops = new GradientStopCollection()
    {
        a,b
    };
        CounterBtn.Background = ll;
    }

Original answer