How to allow a user to click on TextBlocks which return an integer ID in the click handler

本文介绍如何使用WPF中的TextBlock实现按钮功能,通过设置样式使其响应鼠标点击事件,并利用Tag属性传递额外信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This example shows you how to use the Tag attribute, the MouseDown event, and EventSetter in a style to make alist of TextBlocks which act as buttons with on a WPF page.
XAML:
<Window x:Class="Test239992.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <Style TargetType="{x:Type TextBlock}" x:Key="ClickableTextBlockStyle">
            <Setter Property="Foreground" Value="Blue" />
            <Setter Property="Cursor" Value="Hand" />
            <EventSetter Event="MouseDown" Handler="Handle_Click"/>
        </Style>
    </Window.Resources>
    <StackPanel Margin="10">
        <TextBlock Tag="1" Text="Customers" Style="{DynamicResource ClickableTextBlockStyle}"/>
        <TextBlock Tag="2" Text="Appointments" Style="{DynamicResource ClickableTextBlockStyle}"/>
        <TextBlock Tag="3" Text="Addresses" Style="{DynamicResource ClickableTextBlockStyle}"/>
    </StackPanel>
</Window>

Code Behind:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Test239992
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void Handle_Click(object sender, MouseButtonEventArgs e)
        {
            int id = Int32.Parse(((TextBlock)sender).Tag.ToString());
            MessageBox.Show("you chose " + id.ToString());
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值