【问题标题】:Passing button value as command parameter将按钮值作为命令参数传递
【发布时间】:2018-08-17 19:06:20
【问题描述】:

我有一个计算器样式的网格。如何将按钮的文本作为 Xamarin 表单中的命令参数传递:

内容资源

<ContentPage.Resources>
    <ResourceDictionary>
        <Style x:Key="PhoneKeys" TargetType="Button">
            <Setter Property="BackgroundColor" Value="White"/>
            <Setter Property="FontSize" Value="36"/>
            <Setter Property="Command" Value="{Binding Source={x:Reference contactsListView}, Path=BindingContext.TapCommand1}"/>
            <Setter Property="CommandParameter" Value="Pass Button Text"/>
        </Style>
    </ResourceDictionary>
</ContentPage.Resources>

网格布局

<Button Style="{StaticResource PhoneKeys}" Text="1" Grid.Row="1" Grid.Column="0" />
<Button Style="{StaticResource PhoneKeys}" Text="1" Grid.Row="1" Grid.Column="0" />
<Button Style="{StaticResource PhoneKeys}" Text="2" Grid.Row="1" Grid.Column="1" />
<Button Style="{StaticResource PhoneKeys}" Text="3" Grid.Row="1" Grid.Column="2" />
<Button Style="{StaticResource PhoneKeys}" Text="4" Grid.Row="2" Grid.Column="0" />
<Button Style="{StaticResource PhoneKeys}" Text="5" Grid.Row="2" Grid.Column="1" />
<Button Style="{StaticResource PhoneKeys}" Text="6" Grid.Row="2" Grid.Column="2" />
<Button Style="{StaticResource PhoneKeys}" Text="7" Grid.Row="3" Grid.Column="0" />
<Button Style="{StaticResource PhoneKeys}" Text="8" Grid.Row="3" Grid.Column="1" />
<Button Style="{StaticResource PhoneKeys}" Text="9" Grid.Row="3" Grid.Column="2" />
<Button Style="{StaticResource PhoneKeys}" Text="*" Grid.Row="4" Grid.Column="0" />
<Button Style="{StaticResource PhoneKeys}" Text="0" Grid.Row="4" Grid.Column="1" />
<Button Style="{StaticResource PhoneKeys}" Text="#" Grid.Row="4" Grid.Column="2" />

【问题讨论】:

  • 我认为不可能这样。您必须在您的Button 本身上定义您的CommandParameter,或者在您的Button 后面有一些可绑定对象,该对象具有您可以绑定到的属性。
  • 为什么不直接写所有的命令参数呢?正如您已经使用 Text 属性所做的那样。这将花费更少的时间来尝试提出如何以风格制作的答案。但我认为如果你写在 它应该传递整个按钮。如果你写 ,它应该传递文本

标签: xamarin xamarin.forms xamarin.android


【解决方案1】:

使用此语法获取控件的属性 "{x:Reference myButton}" 您可以发送自己的按钮引用以获取完整的按钮对象

风格

    <Setter Property="CommandParameter" Value="{x:Reference myButton}" />

XAML

<Button x:Name="myButton" Style="{StaticResource PhoneKeys}" Text="#" Grid.Row="4" Grid.Column="2" />

定义每个按钮的按钮名称并获取该按钮的对象引用。

public ICommand TapCommand1 => new Command((obj) =>
{
        var button = obj as Button;
        var text = button.Text;
});

或在每个按钮中使用每个按钮名称定义命令参数的最佳方式

        <Button x:Name="myButton" Style="{StaticResource PhoneKeys}" CommandParameter="{x:Reference myButton}" Text="#" Grid.Row="4" Grid.Column="2" />

【讨论】:

    猜你喜欢
    • 2015-02-28
    • 1970-01-01
    • 2023-03-23
    • 2016-02-20
    • 1970-01-01
    • 2022-11-05
    • 1970-01-01
    • 2012-03-25
    • 2013-06-14
    相关资源
    最近更新 更多