Null引用事件的异常

时间:2011-11-14 14:54:54

标签: c# wpf visual-studio events

我正在使用WPF c#应用程序。我有一个包含数据网格的用户控件。 我试图通过鼠标右键从用户控件发送公共事件。 这是创建的公共事件

public event MouseButtonEventHandler datagridMouseClick;

接下来它应该在datagrid的这个事件处理程序上被触发:

private void dataGrid1_MouseDown(object sender, MouseButtonEventArgs e)
{
    DependencyObject dep = (DependencyObject)e.OriginalSource;
    while ((dep != null) &&
    !(dep is DataGridCell) &&
    !(dep is DataGridColumnHeader))
    {
        dep = VisualTreeHelper.GetParent(dep);
    }
    if (dep is DataGridCell)
    {
        cell = dep as DataGridCell;
        while ((dep != null) && !(dep is DataGridRow))
        {
            dep = VisualTreeHelper.GetParent(dep);
        }
        row = dep as DataGridRow;
    }

    this.datagridMouseClick(sender, e);  // GIVING ERROR
}

它给了我一个NullReferenceException。你可以帮我找出原因吗?在此先感谢,任何帮助表示赞赏 问候

事件在另一个类中处理(另一个项目实际上因为上面是一个dll除外).. 所以它在这里初始化其他类时听了。

public Window1()
    {
       InitializeComponent();      
        search.datagridDoubleClick +=new RoutedEventHandler(search_datagridDoubleClick);
        search.datagridMouseClick += new MouseButtonEventHandler(search_datagridMouseClick); /* Only this one gives error , even if the other one is handled exactly the same way in the code o.O */

    }

其中search是包含上述第一个代码的对象的名称

我认为这里的问题是我正在尝试侦听从另一个类/项目触发的事件(因为第一个代码来自.dll),这样当前类不会初始化侦听器并将其保持为null。虽然我已经在上面的search.datagridDoubleClick上使用了这个EXACT方法并且工作得很好(这很奇怪)。 PS。我不知道-1,听起来对我来说是个有价值的问题,反正......

1 个答案:

答案 0 :(得分:4)

您需要检查某人是否通过检查datagridMouseClick是否与Null不同来订阅您的活动。

if (datagridMouseClick != null)
    this.datagridMouseClick(sender, e);
相关问题