C# WINDOWS MAUI專案 Image/Label 增加點擊事件(Click event)
C# WINDOWS MAUI專案 Image/Label 增加點擊事件(Click event)
GITHUB: https://github.com/jash-git/MAUI_WinAPI_Object_test/tree/main/Code/15
MainPage.xaml code
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiApp1.MainPage">
<ScrollView>
<VerticalStackLayout
Spacing="25"
Padding="30,0"
VerticalOptions="Center">
<Image
Source="dotnet_bot.png"
SemanticProperties.Description="Cute dot net bot waving hi to you!"
HeightRequest="200"
HorizontalOptions="Center">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped_1" />
</Image.GestureRecognizers>
</Image>
<Label
x:Name="lb01"
Text="Hello, World!"
SemanticProperties.HeadingLevel="Level1"
FontSize="32"
HorizontalOptions="Center" />
<Label
Text="Welcome to .NET Multi-platform App UI"
SemanticProperties.HeadingLevel="Level2"
SemanticProperties.Description="Welcome to dot net Multi platform App U I"
FontSize="18"
HorizontalOptions="Center">
<Label.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" />
</Label.GestureRecognizers>
</Label>
<Button
x:Name="CounterBtn"
Text="Click me"
SemanticProperties.Hint="Counts the number of times you click"
Clicked="OnCounterClicked"
HorizontalOptions="Center" />
</VerticalStackLayout>
</ScrollView>
</ContentPage>
MainPage.xaml.cs code
namespace MauiApp1;
public partial class MainPage : ContentPage
{
int count = 0;
public MainPage()
{
InitializeComponent();
lb01.GestureRecognizers.Add(new TapGestureRecognizer
{
Command = new Command(() =>
{
// 在這裡處理點擊事件
// 可以執行您想要的操作
// 例如,顯示一個對話框或導航到另一個頁面
DisplayAlert("提示", "標籤被點擊了!", "確定");
})
});
}
private void OnCounterClicked(object sender, EventArgs e)
{
count++;
if (count == 1)
CounterBtn.Text = $"Clicked {count} time";
else
CounterBtn.Text = $"Clicked {count} times";
SemanticScreenReader.Announce(CounterBtn.Text);
}
private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
DisplayAlert("提示", "標籤被點擊了!", "確定");
}
private void TapGestureRecognizer_Tapped_1(object sender, EventArgs e)
{
DisplayAlert("提示", "圖片被點擊了!", "確定");
}
}