8

I have a page who's sole purpose is to get the user to enter their display name into an Entry box, then click a button which will move the user on to the next page.

            <Grid.RowDefinitions>
                <RowDefinition Height="0.10*"/>
                <RowDefinition Height="0.20*"/>
                <RowDefinition Height="0.15*"/>
                <RowDefinition Height="0.40*"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <Label Style="LargeRegularLabel" Text="Enter Your Display Name:" 
                   Grid.Row="1" VerticalOptions="End" HorizontalOptions="Start"/>
            <Entry x:Name="DisplayNameEntry" Grid.Row ="2" 
                   Placeholder="Enter Name Here" 
                   Text="{Binding DisplayName, Mode=TwoWay}" />
            <Button x:Name="BeginButton" Text="Begin Quiz" 
                    Grid.Row="4" 
                    HorizontalOptions="Center" VerticalOptions="Center" 
                    Command="{StaticResource BeginQuizButtonCommand}" CommandParameter="{Binding Source=DisplayNameEntry,  Path=Text}"/>
        </Grid>

In the above XAML I have this.

CommandParameter="{Binding Source=DisplayNameEntry,  Path=Text}"

I hoped that would allow me grab the text from the Entry box when the button was clicked and pass it as a parameter to the relevant Command then onto the relevant method in the ViewModel that determines if it's a valid name.

However it seems to just be passing nothing to the Command. When I place a breakpoint in the Execute() method of the command I can see the parameter's value is null.

How do I get this text from the Entry using XAML?

  • 3
    You need to get the reference on the element and then select the property `Source=DisplayNameEntry` will just search it in the BindingContext. Reference can be made as - `CommandParameter="{Binding Source={x:Reference DisplayNameEntry}, Path=Text}"` – memsranga Oct 18 '18 at 13:50
  • @Shan That worked, thank you very much. –  Oct 18 '18 at 13:55
  • Or you could just Bind `DisplayName` to both, since it is already has two way binding. – memsranga Oct 18 '18 at 13:58
  • 2
    Use ElementName instead of Source. `{Binding ElementName=DisplayNameEntry, Path=Text}` – JohnnyQ Oct 18 '18 at 14:10
  • @Shan, you should answer the question properly with your comment so it can be marked as the answer. – Lindsay Oct 18 '18 at 22:19

1 Answers1

12

You need to get the reference on the element and then select the property Source=DisplayNameEntry will just search it in the BindingContext.

CommandParameter="{Binding Source={x:Reference DisplayNameEntry}, Path=Text}"

As @JohnnyQ mentioned you could also use ElementName. I suggest you go through this post on the difference between them

memsranga
  • 1,088
  • 7
  • 13