Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put a MouseDown event in a Style?

This works:

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>

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

But how do I put the MouseDown event in a style, this gives me the error "Cannot find the Style Property 'MouseDown' on the type 'System.Windows.Controls.TextBlock'":

<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>
like image 369
Edward Tanguay Avatar asked Jan 26 '10 13:01

Edward Tanguay


1 Answers

Try EventSetter :)

    <Style TargetType="{x:Type TextBlock}" x:Key="ClickableTextBlockStyle">
        <EventSetter Event="MouseDown" Handler="Handle_Click" />
    </Style>
like image 58
Arcturus Avatar answered Nov 08 '22 12:11

Arcturus