C# WINDOWS MAUI專案 ListView包含 Image & Label 兩個元件 並且綁定三個元件各自的事件函數
C# WINDOWS MAUI專案 ListView包含 Image & Label 兩個元件 並且綁定三個元件各自的事件函數
GITHUB:https://github.com/jash-git/MAUI_WinAPI_Object_test/tree/main/Code/17
實驗結果紀錄:主元件的事件會在子元件事件之前被觸發
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="Maui_ListView.MainPage"> <ScrollView> <VerticalStackLayout Spacing="25" Padding="30,0" VerticalOptions="Center"> <ListView x:Name="lvUser" Margin="20" SelectionMode="Single" BackgroundColor="White" ItemSelected="lvUser_ItemSelected"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <!-- ListView 資料結構標準: ListView.ItemTemplate -> DataTemplate -> ViewCell--> <StackLayout Orientation="Horizontal"> <Image Source="{Binding Image}" WidthRequest="100" HeightRequest="100"> <Image.GestureRecognizers> <TapGestureRecognizer Tapped="OnImageClicked" /> </Image.GestureRecognizers> </Image> <Label Text="{Binding user_account}" FontSize="26" VerticalTextAlignment="Center"> <Label.GestureRecognizers> <TapGestureRecognizer Tapped="OnLabelClicked" /> </Label.GestureRecognizers> </Label> </StackLayout> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView> </VerticalStackLayout> </ScrollView> </ContentPage>
MainPage.xaml.cs code
namespace Maui_ListView; public class LoginItem { public string role_sid { get; set; } public string Image { get; set; } public string user_account { get; set; } public string user_pwd { get; set; } public string employee_no { get; set; } public string SID { get; set; } } public partial class MainPage : ContentPage { int count = 0; public MainPage() { InitializeComponent(); List<LoginItem> items = new List<LoginItem>(); for(int i=0; i<10; i++) { LoginItem loginItemBuf = new LoginItem(); loginItemBuf.role_sid = $"0000{i}"; loginItemBuf.Image = "dotnet_bot.png"; loginItemBuf.user_account = $"0000{i}"; items.Add(loginItemBuf); } lvUser.ItemsSource = items; } private async void OnLabelClicked(object sender, EventArgs e) {//子元件事件 await DisplayAlert("LabelClicked", ((Label)(sender)).Text, "確定"); } private async void OnImageClicked(object sender, EventArgs e) {//子元件事件 await DisplayAlert("ImageClicked", ((Image)(sender)).Source.ToString(), "確定"); ((Image)(sender)).Source = ImageSource.FromFile("user.png");//換圖 } private async void lvUser_ItemSelected(object sender, SelectedItemChangedEventArgs e) {//主元件的事件 if (e.SelectedItem == null) return; LoginItem selectedItem = (LoginItem)e.SelectedItem; await DisplayAlert("ItemSelected", selectedItem.role_sid, "確定"); } }