Search code examples
xamarin.formslabelwidthunderlinestacklayout

Xaamrin Forms BoxView Width Too Long when using to Underline


I am using a BoxView to accomplish underlining in my app. I have a couple of labels that are very short - Text such as Yes or No etc. Here is the XAML for one of the labels with the BoxView for underlining:

<StackLayout Orientation="Vertical" Grid.Row="5" Grid.Column="1" Margin="0,4,0,4" HorizontalOptions="Start" BackgroundColor="Purple" MinimumWidthRequest="1">
    <Label x:Name="txtUseMetric" TextColor="Blue" FontSize="Small" Text="{Binding UseMetricText}" BackgroundColor="Yellow">
    <Label.GestureRecognizers>
        <TapGestureRecognizer Tapped="Value_Tapped" CommandParameter="usemetric" />
    </Label.GestureRecognizers>
    </Label>
    <BoxView BackgroundColor="Green" HeightRequest="1" MinimumWidthRequest="1" />
</StackLayout>

My problem is that the width of the BoxView is always extending past my text I have tried overriding the MinWidthRequest in my App.Xaml file as seen below:

<Style TargetType="BoxView">
    <Setter Property="MinimumWidthRequest" Value="3" />
</Style>

But this has not effect. I have included screen shots for you to see.

FYI - The yellow is the width of the Label. You don't see any purple (the background color of the StackLayout) because the StackLayout and Label are the same width. The second screen shot shows what the screen looks like if I remove the BoxView - i.e. the Label and StackLayout are sized correctly.

Any suggestions on how to fix this?

Screen shot with BoxView Too Long making label and StackLayout too long Screen shot with BoxView Too Long

Screen shot with BoxView removed and Label and Stack Layout sizing correctly enter image description here


Solution

  • Please note the default HorizontalOptions and that Label derives from View:

    Default value is LayoutOptions.Fill unless otherwise documented.

    Add HorizontalOptions="Start" on the "Use Metric" Label:

    <Label x:Name="txtUseMetric" TextColor="Blue" FontSize="Small" 
           Text="{Binding UseMetricText}" BackgroundColor="Yellow"
           HorizontalOptions="Start">
    <BoxView BackgroundColor="Green" HeightRequest="1" 
             WidthRequest="{Binding Path=Width, Source={x:Reference txtUseMetric}" 
             HorizontalOptions="Start"/>