【问题标题】:How can I pass Entry.Text as a CommandParameter of a Button in XAML?如何在 XAML 中将 Entry.Text 作为按钮的 CommandParameter 传递?
【发布时间】:2019-03-23 08:07:43
【问题描述】:

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

            <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>

在上面的 XAML 中我有这个。

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

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

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

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

【问题讨论】:

  • 您需要获取元素上的引用,然后选择属性Source=DisplayNameEntry 只会在 BindingContext 中搜索它。可以参考-CommandParameter="{Binding Source={x:Reference DisplayNameEntry}, Path=Text}"
  • @Shan 成功了,非常感谢。
  • 或者你可以将DisplayName绑定到两者,因为它已经有双向绑定了。
  • 使用 ElementName 而不是 Source。 {Binding ElementName=DisplayNameEntry, Path=Text}
  • @Shan,您应该用您的评论正确回答问题,以便将其标记为答案。

标签: xaml xamarin data-binding xamarin.forms


【解决方案1】:

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

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

正如@JohnnyQ 提到的,您也可以使用ElementName。我建议你在difference between them上阅读这篇文章

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    相关资源
    最近更新 更多