Get (and bind to) current displaywidth of element in Maui

565 Views Asked by At

In my xaml setup I have a Label, which should wrap its text. It is contained within a border, and I want the Label width to be the width of the border. I've tried to do this with the following binding on the label:

WidthRequest="{Binding Source={RelativeSource Mode=FindAncestor, AncestorType={x:Type Border}}, Path=Width}"

This has not worked though, and i suspect it hasn't because the Width that gets returned is NaN (I've written out the width of the border during runtime and it was NaN). But this is confusing to me, as I have a binding on the Border to the width of the Flexlayout which is working. Is there anything I'm missing and is there any better way to do this?

xaml:

        <ScrollView Grid.Row="1">
            <FlexLayout BindableLayout.ItemsSource="{Binding DisplayedUserActions}" JustifyContent="Start" Wrap="Wrap" Direction="Row">  
                <BindableLayout.ItemTemplate>
                    <DataTemplate>                      
                         <Border FlexLayout.AlignSelf="Stretch" FlexLayout.Basis="{Binding Source={RelativeSource FindAncestor, AncestorType{x:Type ScrollView}}, Path=Width, Converter={StaticResource WidthToFlexlayoutBasisConverter}}">
                             <Grid RowDefinitions="*,*">
                                  -- more content --
                                  <Label Grid.Row="1" Text="{Binding Title}" LineBreakMode="WordWrap" HorizontalTextAlignment="Center" VerticalOptions="Center" HorizontalOptions="Center" TextColor="Black" Margin="5" WidthRequest="{Binding Source={RelativeSource Mode=FindAncestor, AncestorType={x:Type Border}}, Path=Width}"/>
                             </Grid>
                         </Border>
                    </DataTemplate>
                </BindableLayout.ItemTemplate>
            </FlexLayout>
        </ScrollView>
1

There are 1 best solutions below

0
Zack On

You can use data binding to achieve the same width for Label and Border. Bind the Border and Label's WidthRequest properties to the TestWidth property in the same binding context. like this:

Xaml:

<StackLayout>
        <StackLayout.BindingContext>
            <local:MyViewModel/>
        </StackLayout.BindingContext>

        <Border BackgroundColor="Pink" WidthRequest="{Binding Testwidth}">
            <Label x:Name="lable" Text="test1111111111111111" WidthRequest="{Binding Testwidth}"/>
        </Border>
</StackLayout>

ViewModel:

public class MyViewModel : INotifyPropertyChanged
{
    public double testwidth;
    public event PropertyChangedEventHandler PropertyChanged;
    public double Testwidth
    {
        get { return testwidth; }
        set
        {
            if (testwidth != value)
            {
                testwidth = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Testwidth"));
            }
        }
    }
    public MyViewModel() { testwidth= 100; }
}