动态分配事件

发布于 2024-12-08 02:38:21 字数 465 浏览 0 评论 0原文

我正在动态创建一个 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");
}

I am dynamically creating a GroupBox and trying to assign the MouseLeftButtonDown event to it to perform some action when the user left-clicks on it. This is what I've tried:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

娇俏 2024-12-15 02:38:21

handler 方法中有 __(双下划线)。

void tagGroupBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
}

There are __ (double underscores) in handler method.

void tagGroupBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
}
似狗非友 2024-12-15 02:38:21

这对我有用:

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>

This works for me:

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文