共用方式為


如何:在混合應用程式中啟用視覺化樣式

本主題說明如何在裝載于 WPF 應用程式之 Windows Forms 控制項上啟用視覺化樣式。

如果您的應用程式呼叫 EnableVisualStyles 方法,大部分的 Windows Forms 控制項都會自動使用視覺化樣式。 如需詳細資訊,請參閱使用視覺化樣式轉譯控制項

如需本主題中所述工作的完整程式碼清單,請參閱 Enabling Visual Styles in a Hybrid Application Sample (在混合應用程式範例中啟用視覺化樣式)。

啟用 Windows Forms 視覺化樣式

啟用 Windows Forms 視覺化樣式

  1. 建立名為 HostingWfWithVisualStyles 的 WPF 應用程式專案。

  2. 在 [方案總管] 中,加入下列組件的參考。

    • WindowsFormsIntegration

    • System.Windows.Forms

  3. 在 [工具箱] 中 Grid ,按兩下圖示,將專案放在 Grid 設計介面上。

  4. 在屬性視窗中,將 和 屬性的值 Height 設定為 [自動 ]。 Width

  5. 在 [設計檢視] 或 [XAML] 檢視中 Window ,選取 。

  6. 在 [屬性] 視窗中,按一下 [事件] 索引標籤。

  7. 按兩下 Loaded 事件。

  8. 在 MainWindow.xaml.vb 或 MainWindow.xaml.cs 中,插入下列程式碼來處理 Loaded 事件。

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        // Comment out the following line to disable visual
        // styles for the hosted Windows Forms control.
        System.Windows.Forms.Application.EnableVisualStyles();
    
        // Create a WindowsFormsHost element to host
        // the Windows Forms control.
        System.Windows.Forms.Integration.WindowsFormsHost host =
            new System.Windows.Forms.Integration.WindowsFormsHost();
    
        // Create a Windows Forms tab control.
        System.Windows.Forms.TabControl tc = new System.Windows.Forms.TabControl();
        tc.TabPages.Add("Tab1");
        tc.TabPages.Add("Tab2");
    
        // Assign the Windows Forms tab control as the hosted control.
        host.Child = tc;
    
        // Assign the host element to the parent Grid element.
        this.grid1.Children.Add(host);
    }
    
    Private Sub Window_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
        ' Comment out the following line to disable visual
        ' styles for the hosted Windows Forms control.
        System.Windows.Forms.Application.EnableVisualStyles()
    
        ' Create a WindowsFormsHost element to host
        ' the Windows Forms control.
        Dim host As New System.Windows.Forms.Integration.WindowsFormsHost()
    
        ' Create a Windows Forms tab control.
        Dim tc As New System.Windows.Forms.TabControl()
        tc.TabPages.Add("Tab1")
        tc.TabPages.Add("Tab2")
    
        ' Assign the Windows Forms tab control as the hosted control.
        host.Child = tc
    
        ' Assign the host element to the parent Grid element.
        Me.grid1.Children.Add(host)
    
    End Sub
    
  9. 按 F5 以建置並執行應用程式。

    Windows Forms 控制項會以視覺化樣式繪製。

停用 Windows Forms 視覺化樣式

若要停用視覺化樣式,只要移除方法的 EnableVisualStyles 呼叫即可。

停用 Windows Forms 視覺化樣式

  1. 在程式碼編輯器中,開啟 MainWindow.xaml.vb 或 MainWindow.xaml.cs。

  2. 將 方法的 EnableVisualStyles 呼叫批註化。

  3. 按 F5 以建置並執行應用程式。

    Windows Forms 控制項會使用預設系統樣式繪製。

另請參閱