如何将 MouseDown 事件放入样式中?

2024-05-08

这有效:

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">
    <StackPanel>
        <TextBlock Tag="1" Text="Customers" MouseDown="Handle_Click"/>
        <TextBlock Tag="2" Text="Appointments" MouseDown="Handle_Click"/>
    </StackPanel>
</Window>

背后代码:

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 " + id.ToString());
        }
    }
}

But 如何将 MouseDown 事件放入样式中,这给了我error“在类型‘System.Windows.Controls.TextBlock’上找不到样式属性‘MouseDown’”:

<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="MouseDown" Value="Handle_Click" />
        </Style>
    </Window.Resources>
    <StackPanel>
        <TextBlock Tag="1" Text="Customers" Style="{DynamicResource ClickableTextBlockStyle}"/>
        <TextBlock Tag="2" Text="Appointments" Style="{DynamicResource ClickableTextBlockStyle}"/>
    </StackPanel>
</Window>

Try 事件设置者 http://msdn.microsoft.com/en-us/library/system.windows.eventsetter.aspx :)

    <Style TargetType="{x:Type TextBlock}" x:Key="ClickableTextBlockStyle">
        <EventSetter Event="MouseDown" Handler="Handle_Click" />
    </Style>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 MouseDown 事件放入样式中? 的相关文章

随机推荐