MAUI 怎么给控件加上单击事件
MAUI上的点击事件是通过笔势的点击实现
官方文档路径
识别点击手势 - .NET MAUI | Microsoft Learn
下面是个案例
XAML:
<Image Source="asdf.jpg" Grid.ColumnSpan="3" Margin="5" > <Image.GestureRecognizers> <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"></TapGestureRecognizer> </Image.GestureRecognizers> </Image>
c#:
/// <summary> /// 给image加的点击事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TapGestureRecognizer_Tapped(object sender, EventArgs e) { }
可以通过ICommand 传参
<Image Source="asdf.jpg" Grid.ColumnSpan="3" Margin="5" > <Image.GestureRecognizers> <TapGestureRecognizer Command="{Binding ClickCommand}" CommandParameter="{Binding}"></TapGestureRecognizer> </Image.GestureRecognizers> </Image>
创建一个MVVM的实体模型
public class CommandModel { private ICommand _clickCommand; public ICommand ClickCommand { get { return _clickCommand; } set { _clickCommand = value; } } }
绑定实体模型和事件的回调
public Category() { InitializeComponent(); var model = new CommandModel(); model.ClickCommand = new Command(TestCommond); ; this.BindingContext = model; }
/// <summary> /// 单击事件 /// </summary> /// <param name="sender"></param> public void TestCommond(object sender) { }