繁体   English   中英

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

[英]How to put a MouseDown event in a Style?

这有效:

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());
        }
    }
}

但是我如何将MouseDown事件放在一个样式中 ,这给了我错误 “无法在类型'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>

试试EventSetter :)

    <Style TargetType="{x:Type TextBlock}" x:Key="ClickableTextBlockStyle">
        <EventSetter Event="MouseDown" Handler="Handle_Click" />
    </Style>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM