【问题标题】:Virtual MouseButtonEventHandler in my DLL overridden from calling application我的 DLL 中的虚拟 MouseButtonEventHandler 被调用应用程序覆盖
【发布时间】:2019-03-02 01:15:57
【问题描述】:

我有我的类库,它在网格中动态创建标签

public class Class1
{
        public virtual event System.Windows.Input.MouseButtonEventHandler label_event;

        public Class1(Grid _grid)
        {
            Label l = new Label();
            l.Content = "label";
            l.Cursor = System.Windows.Input.Cursors.Hand;
            Grid.SetColumn(_grid, 0);
            Grid.SetRow(_grid, 0);
            _grid.Children.Add(l);

            l.MouseLeftButtonUp += label_event;
        }
}

这个类是从另一个应用程序创建的

Class1 class1 = new Class1(grid);
class1.label_event += l_MouseLeftButtonUp;
...
void l_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
       Title = sender.ToString();
}
...

编译没有错误,但是执行后l.MouseLeftButtonUp += label_event; "Cannot be null" 有错误

如何覆盖鼠标事件?

【问题讨论】:

    标签: wpf events overriding virtual


    【解决方案1】:

    您应该在Class1 中引发一个事件,然后在消费类中处理它:

    public class Class1
    {
        public event System.Windows.Input.MouseButtonEventHandler label_event;
    
        public Class1(Grid _grid)
        {
            Label l = new Label();
            l.Content = "label";
            l.Cursor = System.Windows.Input.Cursors.Hand;
            Grid.SetColumn(_grid, 0);
            Grid.SetRow(_grid, 0);
            _grid.Children.Add(l);
    
            l.MouseLeftButtonUp += (s,e) => label_event?.Invoke(this, e);
        }
    }
    

    【讨论】:

    • 谢谢你的想法,但这段代码不是为我编译的,但这没关系 l.MouseLeftButtonUp += (s, e) => { if (label_event != null) label_event.Invoke(s , e); };
    猜你喜欢
    • 1970-01-01
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 2012-06-15
    • 1970-01-01
    相关资源
    最近更新 更多