How to make a horizontally centered Entry expand to be just wide enough to show it's entire Text ?

John Hardman 261 Reputation points
2021-02-09T17:21:31.59+00:00

How can one reliably implement a horizontally centered Entry that expands to the width required to show its Text, without expanding beyond that?
(I want a readonly Entry of the minimum width that shows its entire Text, where the readonly Entry is centered horizontally on the page).

Some code that demonstrates an Entry with HorizontalOptions = CenterAndExpand but where the Entry does not expand to show its entire Text can be found at https://xamarin.github.io/bugzilla-archives/59/59391/bug.html

TBH, I do have a hacky workaround, that involves using a Grid to overlay the Entry on a Label that has its Text property bound to the same property on the ViewModel as the Entry, but that's hacky as I have to apply a Margin to the Label using some magic numbers. In that hacky workaround, the Label expands to show the entire Text, resulting in the Grid expanding, resulting in the Entry also expanding. I'd rather have a solution that doesn't involve magic numbers.

(cross posted from https://forums.xamarin.com/discussion/187359/how-to-make-a-horizontally-centered-entry-expand-to-be-just-wide-enough-to-show-its-entire-text )

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,367 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Cole Xia (Shanghai Wicresoft Co,.Ltd.) 6,751 Reputation points
    2021-02-10T06:53:05.19+00:00

    Hello,

    Welcome to Microsoft Q&A!

    Try to use a Grid to Wrap label and Entry, create the binding between label and entry (Text , FontSize , WidthRequest), then change the text of the label , the label auto expand and result in the entry expanding .

       <Grid >  
               <Label  Text="123" BackgroundColor="Green"  x:Name="label" HorizontalOptions="CenterAndExpand" />  
               <Entry  x:Name="entry" BackgroundColor="Red" HorizontalOptions="CenterAndExpand"          
                       BindingContext="{x:Reference label}"  
                       Text="{Binding Text}"  
                       FontSize="{Binding FontSize}"  
                       WidthRequest="{Binding Width}"/>  
           </Grid>  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.