Avalonia 多個按鈕(button)和 標籤/非按鈕UI元件(TextBlock) 使用程式方式綁訂定滑鼠點擊事件函數範例
Avalonia 多個按鈕(button)和 標籤/非按鈕UI元件(TextBlock) 使用程式方式綁訂定滑鼠點擊事件函數範例
資料來源: copilot
多個按鈕(button):
多個非按鈕UI元件(TextBlock) :
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using System;
public class Example
{
public Example()
{
// 創建一個StackPanel來放置TextBlock
var panel = new StackPanel();
// 創建多個TextBlock並綁定點擊事件
for (int i = 0; i < 5; i++)
{
var textBlock = new TextBlock
{
Text = $"TextBlock {i + 1}",
Margin = new Thickness(5),
Foreground = Brushes.Black
};
textBlock.PointerPressed += OnTextBlockClick;//綁定事件函數
panel.Children.Add(textBlock);//容器(版面配置~Grid)新增UI元素
}
// 將StackPanel設置為視圖的內容
var window = new Window
{
Content = panel
};
window.Show();
}
private void OnTextBlockClick(object sender, PointerPressedEventArgs e)
{
var textBlock = sender as TextBlock;
if (textBlock != null)
{
Console.WriteLine($"{textBlock.Text} clicked");
}
}
}