如何在 XAML 中将 Entry.Text 作为按钮的 CommandParameter 传递?

6 data-binding xaml xamarin xamarin.forms

我有一个页面,其唯一目的是让用户在输入框中输入他们的显示名称,然后单击一个按钮,将用户移动到下一页。

            <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>
Run Code Online (Sandbox Code Playgroud)

在上面的 XAML 中,我有这个。

CommandParameter="{Binding Source=DisplayNameEntry,  Path=Text}"
Run Code Online (Sandbox Code Playgroud)

我希望这能让我在单击按钮时从 Entry 框中获取文本并将其作为参数传递给相关的 Command,然后传递给 ViewModel 中的相关方法,以确定它是否为有效名称。

然而,它似乎只是没有传递给命令。当我在命令的 Execute() 方法中放置断点时,我可以看到参数的值为空。

如何使用 XAML 从条目中获取此文本?

mem*_*nga 7

您需要获取对元素的引用,然后选择该属性Source=DisplayNameEntry将在 BindingContext 中搜索它。

CommandParameter="{Binding Source={x:Reference DisplayNameEntry}, Path=Text}"
Run Code Online (Sandbox Code Playgroud)

正如@JohnnyQ 提到的,你也可以使用ElementName. 我建议你通过这篇文章了解它们之间区别