动态分配事件

时间:2011-10-06 01:57:08

标签: c# wpf event-handling

我正在动态创建一个GroupBox并尝试将MouseLeftButtonDown事件分配给它,以便在用户左键单击它时执行某些操作。这就是我尝试过的:

public MyClass()
{
    tagGroupBox.MouseLeftButtonDown += new MouseButtonEventHandler(tagGroupBox_MouseLeftButtonDown);  //generates error: "tagGroupBox_MouseLeftButtonDown does not exist in the current context"
}

private void tagGroupBox__MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
     MessageBox.Show("Left click event triggered");
}

2 个答案:

答案 0 :(得分:4)

处理程序方法中有__(双下划线)。

void tagGroupBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
}

答案 1 :(得分:0)

这对我有用:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        GroupBox g = new GroupBox();
        g.MouseLeftButtonUp += new MouseButtonEventHandler(g_MouseLeftButtonUp);
        MainGrid.Children.Add(g);
    }

    void g_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        System.Diagnostics.Debugger.Break();
    }
}

XAML

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid x:Name="MainGrid">

    </Grid>
</Window>