如何正确地将Windows表单对象公开给其他类

时间:2016-05-19 09:47:56

标签: wpf vb.net vsto

我有一个基本问题。我正在创建一个VSTO Word Addin。我有一个功能区按钮,打开一个名为TableSelector的WPF对话框。它以Windows窗体托管。

Public Class RibbonControl

Private f As Form

Private Sub btnSelectTable_Click(sender As Object, e As RibbonControlEventArgs) Handles btnSelectTable.Click
    Dim h As New System.Windows.Forms.Integration.ElementHost()
    Dim tableselector1 As New TableSelector
    f = New Form()
    f.MaximumSize = New Size(500, 380)
    f.MinimumSize = New Size(500, 380)
    f.MaximizeBox = False
    f.Name = "HostForm"
    h.Dock = DockStyle.Fill
    h.Child = tableselector1
    f.Controls.Add(h)
    f.Show()
    f.TopMost = True
End Sub

Public ReadOnly Property hostForm() As Form
    Get
        Return f
    End Get
End Property

End Class

然后我在该WPF控件上有一个关闭按钮以关闭对话框。当我单击它时,我得到运行时错误"对象引用未设置为对象的实例。"在以下代码的第3行。

Private Sub btnClose_Click(sender As Object, e As RoutedEventArgs) Handles btnClose.Click
    Dim ribbon As New RibbonControl()
    ribbon.hostForm.Close()
End Sub

我错过了什么?

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码获取关闭的特定窗口

Window win = Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.Name == "Window Name");
win.Close();