【问题标题】:How can an external event be known in one sub and not in another, in the same class?如何在同一类中的一个子中而不是在另一个子中知道外部事件?
【发布时间】:2014-09-17 10:52:34
【问题描述】:

图片可能最好地说明了我的问题。

Sub New 中,CompositionTarget.Rendering 是众所周知的,但我坚持使用 C# 语法。 VB.NET 很难!然而在CompositionTargetRendering 中,编译器以前从未遇到过它。它在 System.Windows.Media 中声明,我的导入中肯定有它。

我对处理程序的声明不正确还是什么?或者是Xenu在惹我吗>

哦,是的,我正在翻译的 C# 编译得很好:

    CompositionTarget.Rendering += CompositionTargetRendering;
    private void CompositionTargetRendering(object sender, EventArgs e)
    {
        if (stopwatch.ElapsedMilliseconds > lastUpdateMilliSeconds + 5000)
        {
            viewModel.UpdateModel();
            Plot1.RefreshPlot(true);
            lastUpdateMilliSeconds = stopwatch.ElapsedMilliseconds;
        }
    }

【问题讨论】:

    标签: .net vb.net events event-handling c#-to-vb.net


    【解决方案1】:

    您无需在 VB.NET 中使用 += 添加处理程序,您需要:

    声明对象WithEvents并使用Handles关键字

    Private WithEvents MyCompositionTarget As CompositionTarget
    
    Private Sub CompositionTargetRendering() Handles MyCompositionTarget.Rendering
         'code for event here
    End Sub
    

    或使用AddHandler(其工作方式与C# += 相同)(不要使用Handles 关键字)

    Private MyCompositionTarget As CompositionTarget
    
    Publlic Sub New
        AddHandler MyCompositionTarget.Rendering, AddressOf CompositionTargetRendering
    End Sub
    
    Private Sub CompositionTargetRendering()
         'code for event here
    End Sub
    

    【讨论】:

    • 是的,我知道;我说 += 是对我的 C# 舒适区的回归。我不能声明CompositionTargetWithEvents,它是System.Windows.Media 中的一个抽象类。但是谢谢 - 我忘记了 AddHandler,现在编译器喜欢我的代码。
    猜你喜欢
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 2011-02-27
    相关资源
    最近更新 更多