我正在动态地创建一个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");
}
handler方法中有__(双下划线)
void tagGroupBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
}
这个适合我:
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>