我有一个计算器样式网格。如何在Xamarin Forms中将按钮的文本作为命令参数传递:
内容资源
<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" />
答案 0 :(得分:0)
使用此语法获取控件“ {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" />