如何:在混合应用程序中启用视觉样式

本主题演示如何在基于 WPF 的应用程序中托管的 Windows 窗体控件上启用视觉样式。

如果应用程序调用该方法 EnableVisualStyles ,大多数 Windows 窗体控件将自动使用视觉样式。 有关详细信息,请参阅 使用视觉样式呈现控件

有关本主题中演示的任务的完整代码列表,请参阅 混合应用程序示例中的“启用视觉样式”。

启用 Windows 窗体视觉样式

启用 Windows 窗体视觉样式

  1. 创建名为 HostingWfWithVisualStyles的 WPF 应用程序项目。

  2. 在解决方案资源管理器中,添加对以下程序集的引用。

    • WindowsFormsIntegration

    • System.Windows.Forms

  3. 在工具箱中,双击 Grid 图标将元素放置在 Grid 设计图面上。

  4. 在“属性”窗口中,将属性的值HeightWidth设置为“自动”。

  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 窗体控件采用视觉风格进行绘制。

禁用 Windows 窗体视觉样式

若要禁用视觉样式,只需删除对方法的 EnableVisualStyles 调用。

禁用 Windows 窗体视觉样式

  1. 在代码编辑器中打开MainWindow.xaml.vb或MainWindow.xaml.cs。

  2. 注释掉对方法的 EnableVisualStyles 调用。

  3. 按 F5 生成并运行应用程序。

    Windows 窗体控件使用默认系统样式绘制。

另请参阅