2011-10-06 87 views
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"); 
} 

回答

4

有__(雙下劃線)。

void tagGroupBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) 
{ 
} 
+0

哇,我真不敢相信我錯過了。感謝您的發現! – kr13

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>