.NET KeyUp处理程序:是否没有必要将发件人转换为正确的类型?

时间:2015-05-23 11:23:33

标签: .net wpf vb.net casting handler

我目前正在重构我的VB.NET应用程序,并碰到了一些我没想到的东西。有两个KeyUp事件处理程序,代码大部分是相同的,我希望减少到1个事件处理程序。其中一个处理程序由WPF ListBox使用,另一个由WPF DataGrid使用。这些是处理程序:

Protected Sub ListBox_KeyUp(sender As Object, e As KeyEventArgs)

    Dim box As ListBox = CType(sender, ListBox)

    If e.Key = Key.J AndAlso Keyboard.Modifiers = ModifierKeys.Control Then
        If box.SelectedItem IsNot Nothing Then
            Actions.TryViewInExplorer(CType(box.SelectedItem, TrackInfoViewModel).TrackInfo.Path)
        End If
    End If
End Sub

Protected Sub DataGrid_KeyUp(sender As Object, e As KeyEventArgs)

    Dim box As DataGrid = CType(sender, DataGrid)

    If e.Key = Key.J AndAlso Keyboard.Modifiers = ModifierKeys.Control Then
        If box.SelectedItem IsNot Nothing Then
            Actions.TryViewInExplorer(CType(box.SelectedItem, TrackInfoViewModel).TrackInfo.Path)
        End If
    End If
End Sub

如您所见,在尝试调用函数“SelectedItem”之前,我将sender对象转换为正确的item容器。 当将这两个处理程序重构为1时,我注意到Visual Studio在直接在发送方上调用“SelectedItem”时没有抛出任何错误而没有先抛出它:

Protected Sub ListBox_KeyUp(sender As Object, e As KeyEventArgs)

    If e.Key = Key.J AndAlso Keyboard.Modifiers = ModifierKeys.Control Then
        If box.SelectedItem IsNot Nothing Then
            Actions.TryViewInExplorer(CType(sender.SelectedItem, TrackInfoViewModel).TrackInfo.Path)
        End If
    End If
End Sub

我没想到这是可能的。这应该是可能的吗?保持这样的解决方案是不错的做法?

0 个答案:

没有答案