Compartilhar via


Demonstra Passo a passo: Hospedando um controle Windows Forms composto no WPF

Atualização: August 2010

Windows Presentation Foundation (WPF) provides a rich environment for creating applications. However, when you have a substantial investment in Windows Forms code, it can be more effective to reuse at least some of that code in your WPF application rather than to rewrite it from scratch. O cenário mais comum é quando você tem a opção existente Windows Forms controles. Em alguns casos, talvez você não ainda tenha acesso ao código-fonte para esses controles. WPFFornece um procedimento simples para hospedar esses controles em um WPF aplicativo. For example, you can use WPF for most of your programming while hosting your specialized DataGridView controls.

Esta explicação passo a passo orienta através de um aplicativo que hospeda um Windows Forms um controle composto para realizar a entrada de dados em um WPF aplicativo. O controle composto é empacotado em uma DLL. This general procedure can be extended to more complex applications and controls. Esta explicação passo a passo é projetada para ser praticamente idêntico em aparência e funcionalidade para Demonstra Passo a passo: Hospedando um controle composto do WPF no Windows Forms. The primary difference is that the hosting scenario is reversed.

The walkthrough is divided into two sections. A primeira seção descreve brevemente a implementação de Windows Forms controle composto. A segunda seção discute em detalhes como hospedar o controle composto em um WPF aplicativo, receber eventos de controle e acessar algumas das propriedades de. o controle

Tasks illustrated in this walkthrough include:

  • Implementando o controle composto do Windows Forms.

  • Implementando o aplicativo host do WPF.

Para obter uma listagem de código completo das tarefas ilustradas nesta explicação, consulte que hospeda um controle Windows Forms composto WPF de exemplo.

Prerequisites

You need the following components to complete this walkthrough:

  • Visual Studio 2010.

A implementação de controle composto do Windows Forms

O Windows Forms um controle composto usado neste exemplo é um formulário de entrada de dados simple. This form takes the user's name and address and then uses a custom event to return that information to the host. The following illustration shows the rendered control.

Controle composto do Windows Forms

Controle simples do Window Forms

Creating the Project

To start the project:

  1. Launch Microsoft Visual Studio, and open the New Project dialog box.

  2. Na categoria de janela, selecione o Windows Forms Control Library modelo.

  3. Nomeie o novo projeto MyControls.

  4. O local, especifique uma pasta de nível superior convenientemente nomeada, como WpfHostingWindowsFormsControl. Posteriormente, você colocará o aplicativo host nesta pasta.

  5. Click OK to create the project. The default project contains a single control named UserControl1.

  6. No Solution Explorer, renomeie UserControl1 para MyControl1.

Your project should have references to the following system DLLs. If any of these DLLs are not included by default, add them to the project.

  • System

  • System.Data

  • System.Drawing

  • System.Windows.Forms

  • System. XML

Adding Controls to the Form

To add controls to the form:

  • Abrir MyControl1 no designer.

Adicionar cinco Label controles e seus correspondentes TextBox controles, dimensionadas e organizadas como eles estão na ilustração anterior, no formulário. In the example, the TextBox controls are named:

  • txtName

  • txtAddress

  • txtCity

  • txtState

  • txtZip

Add two Button controls labeled OK and Cancel. In the example, the button names are btnOK and btnCancel, respectively.

Implementing the Supporting Code

Abra o formulário no modo de exibição de código. The control returns the collected data to its host by raising the custom OnButtonClick event. The data is contained in the event argument object. O código a seguir mostra a declaração de evento e o delegado.

Add the following code to the MyControl1 class.

Public Delegate Sub MyControlEventHandler(ByVal sender As Object, ByVal args As MyControlEventArgs)
Public Event OnButtonClick As MyControlEventHandler
public delegate void MyControlEventHandler(object sender, MyControlEventArgs args);
public event MyControlEventHandler OnButtonClick;

The MyControlEventArgs class contains the information to be returned to the host.

Adicione a seguinte classe ao formulário.

Public Class MyControlEventArgs
    Inherits EventArgs
    Private _Name As String
    Private _StreetAddress As String
    Private _City As String
    Private _State As String
    Private _Zip As String
    Private _IsOK As Boolean


    Public Sub New(ByVal result As Boolean, ByVal name As String, ByVal address As String, ByVal city As String, ByVal state As String, ByVal zip As String) 
        _IsOK = result
        _Name = name
        _StreetAddress = address
        _City = city
        _State = state
        _Zip = zip

    End Sub


    Public Property MyName() As String 
        Get
            Return _Name
        End Get
        Set
            _Name = value
        End Set
    End Property

    Public Property MyStreetAddress() As String 
        Get
            Return _StreetAddress
        End Get
        Set
            _StreetAddress = value
        End Set
    End Property

    Public Property MyCity() As String 
        Get
            Return _City
        End Get
        Set
            _City = value
        End Set
    End Property

    Public Property MyState() As String 
        Get
            Return _State
        End Get
        Set
            _State = value
        End Set
    End Property

    Public Property MyZip() As String 
        Get
            Return _Zip
        End Get
        Set
            _Zip = value
        End Set
    End Property

    Public Property IsOK() As Boolean 
        Get
            Return _IsOK
        End Get
        Set
            _IsOK = value
        End Set
    End Property
End Class
public class MyControlEventArgs : EventArgs
{
    private string _Name;
    private string _StreetAddress;
    private string _City;
    private string _State;
    private string _Zip;
    private bool _IsOK;

    public MyControlEventArgs(bool result,
                                   string name,
                                   string address,
                                   string city,
                                   string state,
                                   string zip)
    {
        _IsOK = result;
        _Name = name;
        _StreetAddress = address;
        _City = city;
        _State = state;
        _Zip = zip;
    }

    public string MyName
    {
        get { return _Name; }
        set { _Name = value; }
    }
    public string MyStreetAddress
    {
        get { return _StreetAddress; }
        set { _StreetAddress = value; }
    }
    public string MyCity
    {
        get { return _City; }
        set { _City = value; }
    }
    public string MyState
    {
        get { return _State; }
        set { _State = value; }
    }
    public string MyZip
    {
        get { return _Zip; }
        set { _Zip = value; }
    }
    public bool IsOK
    {
        get { return _IsOK; }
        set { _IsOK = value; }
    }
}

When the user clicks the OK or Cancel button, the Click event handlers create a MyControlEventArgs object that contains the data and raises the OnButtonClick event. The only difference between the two handlers is the event argument's IsOK property. This property enables the host to determine which button was clicked. It is set to true for the OK button, and false for the Cancel button. O código a seguir mostra os manipuladores de botão de dois.

Add the following code to the MyControl1 class.

Private Sub btnOK_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOK.Click

    Dim retvals As New MyControlEventArgs(True, txtName.Text, txtAddress.Text, txtCity.Text, txtState.Text, txtZip.Text)
    RaiseEvent OnButtonClick(Me, retvals)

End Sub

Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
    Dim retvals As New MyControlEventArgs(False, txtName.Text, txtAddress.Text, txtCity.Text, txtState.Text, txtZip.Text)
    RaiseEvent OnButtonClick(Me, retvals)

End Sub
private void btnOK_Click(object sender, System.EventArgs e)
{

    MyControlEventArgs retvals = new MyControlEventArgs(true,
                                                         txtName.Text,
                                                         txtAddress.Text,
                                                         txtCity.Text,
                                                         txtState.Text,
                                                         txtZip.Text);
    OnButtonClick(this, retvals);
}

private void btnCancel_Click(object sender, System.EventArgs e)
{
    MyControlEventArgs retvals = new MyControlEventArgs(false,
                                                         txtName.Text,
                                                         txtAddress.Text,
                                                         txtCity.Text,
                                                         txtState.Text,
                                                         txtZip.Text);
    OnButtonClick(this, retvals);
}

Giving the Assembly a Strong Name and Building the Assembly

For this assembly to be referenced by a WPF application, it must have a strong name. Para criar um nome forte, crie um arquivo de chave com sn. exe e adicioná-lo ao seu projeto.

  1. Open a Visual Studio command prompt. Para fazer isso, clique o Iniciar menu e selecione todos os programas/Microsoft Visual Studio 2010/Visual Studio Tools/Visual Studio Prompt de comando. This launches a console window with customized environment variables.

  2. No prompt de comando, use o cd comando para ir para a pasta do projeto.

  3. Generate a key file named MyControls.snk by running the following command.

    Sn.exe -k MyControls.snk
    
  4. Para incluir o arquivo de chave em seu projeto, clique com o botão direito no nome do projeto no Solution Explorer e clique em Propriedades. No Project Designer, clique o assinatura guia, selecione o Sign the assembly caixa de seleção e navegue até o arquivo de chave.

  5. Build the solution. The build will produce a DLL named MyControls.dll.

Implementação do aplicativo Host do WPF

The WPF host application uses the WindowsFormsHost control to host MyControl1. The application handles the OnButtonClick event to receive the data from the control. Ele também tem uma coleção de botões de opção que permitem alterar algumas das propriedades do controle a partir de WPF aplicativo. The following illustration shows the finished application.

O aplicativo completo, mostrar o controle incorporado no aplicativo WPF

Um controle inserido em uma página do WPF

Creating the Project

To start the project:

  1. Open Visual Studio, and select New Project.

  2. Na categoria de janela, selecione o Aplicativo WPF modelo.

  3. Nomeie o novo projeto WpfHost.

  4. O local, especifique a mesma pasta de nível superior que contém o projeto MyControls.

  5. Click OK to create the project.

Você também precisará adicionar referências para a DLL que contém MyControl1 e outros assemblies.

  1. Clique com o botão direito no nome do projeto no Solution Explorer e selecione Adicionar referência de.

  2. Clique o Procurar guia e navegue até a pasta que contém MyControls. dll. Para esta explicação, esta pasta é MyControls\bin\Debug.

  3. Selecione MyControls. dll e clique em OK.

  4. Add a reference to the WindowsFormsIntegration assembly, which is named WindowsFormsIntegration.dll.

Implementing the Basic Layout

O user interface (UI) do host do aplicativo é implementado no MainWindow. XAML. Este arquivo contém Extensible Application Markup Language (XAML) marcação que define o layout e hospeda o Windows Forms de controle. O aplicativo é dividido em três regiões:

  • The Control Properties panel, which contains a collection of option buttons that you can use to modify various properties of the hosted control.

  • The Data from Control panel, which contains several TextBlock elements that display the data returned from the hosted control.

  • The hosted control itself.

O layout básico é mostrado na seguinte XAML. A marcação que é necessária para o host MyControl1 omitidos neste exemplo, mas será discutido posteriormente.

Substitua o XAML no MainWindow. XAML com o seguinte. Se você estiver usando Visual Basic, alterar a classe x:Class="MainWindow".

<Window xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
      x:Class="WpfHost.MainWindow"
      xmlns:mcl="clr-namespace:MyControls;assembly=MyControls"
      Loaded="Init">
  <DockPanel>
    <DockPanel.Resources>
      <Style x:Key="inlineText" TargetType="{x:Type Inline}">
        <Setter Property="FontWeight" Value="Normal"/>
      </Style>
      <Style x:Key="titleText" TargetType="{x:Type TextBlock}">
        <Setter Property="DockPanel.Dock" Value="Top"/>
        <Setter Property="FontWeight" Value="Bold"/>
        <Setter Property="Margin" Value="10,5,10,0"/>
      </Style>
    </DockPanel.Resources>

    <StackPanel Orientation="Vertical"
                DockPanel.Dock="Left"
                Background="Bisque"
                Width="250">

      <TextBlock  Margin="10,10,10,10"
                  FontWeight="Bold"
                  FontSize="12">Control Properties</TextBlock>
      <TextBlock Style="{StaticResource titleText}">Background Color</TextBlock>
      <StackPanel Margin="10,10,10,10">
        <RadioButton Name="rdbtnOriginalBackColor"
                    IsChecked="True"
                    Click="BackColorChanged">Original</RadioButton>
        <RadioButton Name="rdbtnBackGreen"
                    Click="BackColorChanged">LightGreen</RadioButton>
        <RadioButton Name="rdbtnBackSalmon"
                    Click="BackColorChanged">LightSalmon</RadioButton>
      </StackPanel>

      <TextBlock Style="{StaticResource titleText}">Foreground Color</TextBlock>
      <StackPanel Margin="10,10,10,10">
        <RadioButton Name="rdbtnOriginalForeColor"
                    IsChecked="True"
                    Click="ForeColorChanged">Original</RadioButton>
        <RadioButton Name="rdbtnForeRed"
                    Click="ForeColorChanged">Red</RadioButton>
        <RadioButton Name="rdbtnForeYellow"
                    Click="ForeColorChanged">Yellow</RadioButton>
      </StackPanel>

      <TextBlock Style="{StaticResource titleText}">Font Family</TextBlock>
      <StackPanel Margin="10,10,10,10">
        <RadioButton Name="rdbtnOriginalFamily"
                     IsChecked="True"
                    Click="FontChanged">Original</RadioButton>
        <RadioButton Name="rdbtnTimes"
                    Click="FontChanged">Times New Roman</RadioButton>
        <RadioButton Name="rdbtnWingdings"
                    Click="FontChanged">Wingdings</RadioButton>
      </StackPanel>

      <TextBlock Style="{StaticResource titleText}">Font Size</TextBlock>
      <StackPanel Margin="10,10,10,10">
        <RadioButton Name="rdbtnOriginalSize"
                    IsChecked="True"
                    Click="FontSizeChanged">Original</RadioButton>
        <RadioButton Name="rdbtnTen"
                    Click="FontSizeChanged">10</RadioButton>
        <RadioButton Name="rdbtnTwelve"
                    Click="FontSizeChanged">12</RadioButton>
      </StackPanel>

      <TextBlock Style="{StaticResource titleText}">Font Style</TextBlock>
      <StackPanel Margin="10,10,10,10">
        <RadioButton Name="rdbtnNormalStyle"
                     IsChecked="True"
                     Click="StyleChanged">Original</RadioButton>
        <RadioButton Name="rdbtnItalic"
                     Click="StyleChanged">Italic</RadioButton>
      </StackPanel>

      <TextBlock Style="{StaticResource titleText}">Font Weight</TextBlock>
      <StackPanel Margin="10,10,10,10">
        <RadioButton Name="rdbtnOriginalWeight"
                     IsChecked="True"
                   Click="WeightChanged">
          Original
        </RadioButton>
        <RadioButton Name="rdbtnBold"
                   Click="WeightChanged">Bold</RadioButton>
      </StackPanel>
    </StackPanel>

    <WindowsFormsHost Name="wfh"
                     DockPanel.Dock="Top"
                     Height="300">
      <mcl:MyControl1 Name="mc"/>
    </WindowsFormsHost>

    <StackPanel Orientation="Vertical"
                Height="Auto"
                Background="LightBlue">
      <TextBlock Margin="10,10,10,10"
            FontWeight="Bold"
            FontSize="12">Data From Control</TextBlock>
      <TextBlock Style="{StaticResource titleText}">
        Name: <Span Name="txtName" Style="{StaticResource inlineText}"/>
      </TextBlock>
      <TextBlock Style="{StaticResource titleText}">
        Street Address: <Span Name="txtAddress" Style="{StaticResource inlineText}"/>
      </TextBlock>
      <TextBlock Style="{StaticResource titleText}">
        City: <Span Name="txtCity" Style="{StaticResource inlineText}"/>
      </TextBlock>
      <TextBlock Style="{StaticResource titleText}">
        State: <Span Name="txtState" Style="{StaticResource inlineText}"/>
      </TextBlock>
      <TextBlock Style="{StaticResource titleText}">
        Zip: <Span Name="txtZip" Style="{StaticResource inlineText}"/>
      </TextBlock>
    </StackPanel>
  </DockPanel>
</Window>

The first StackPanel element contains several sets of RadioButton controls that enable you to modify various default properties of the hosted control. That is followed by a WindowsFormsHost element, which hosts MyControl1. The final StackPanel element contains several TextBlock elements that display the data that is returned by the hosted control. A ordenação dos elementos e a Dock e Height as configurações de atributo incorporar o controle hospedado na janela com lacunas ou distorção.

Hosting the Control

A seguinte versão editada do XAML anterior se concentra nos elementos que são necessários para o host MyControl1.

<Window xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
      x:Class="WpfHost.MainWindow"
      xmlns:mcl="clr-namespace:MyControls;assembly=MyControls"
      Loaded="Init">


...


<WindowsFormsHost Name="wfh"
                 DockPanel.Dock="Top"
                 Height="300">
  <mcl:MyControl1 Name="mc"/>
</WindowsFormsHost>

The xmlns namespace mapping attribute creates a reference to the MyControls namespace that contains the hosted control. This mapping enables you to represent MyControl1 in XAML as <mcl:MyControl1>.

Dois elementos no XAML lidar com a hospedagem:

  • WindowsFormsHostrepresenta o WindowsFormsHost o elemento que permite ao host uma Windows Forms controle em um WPF aplicativo.

  • mcl:MyControl1, which represents MyControl1, is added to the WindowsFormsHost element's child collection. Como resultado, isso Windows Forms controle é processado como parte do WPF janela e você pode se comunicar com o controle do aplicativo.

Implementing the Code-Behind File

O arquivo code-behind, MainWindow.xaml.vb ou MainWindow.xaml.cs, contém o código de procedimento que implementa a funcionalidade da UI discutidos na seção anterior. The primary tasks are:

  • Attaching an event handler to MyControl1's OnButtonClick event.

  • Modifying various properties of MyControl1, based on how the collection of option buttons are set.

  • Displaying the data collected by the control.

Initializing the Application

O código de inicialização está contido em um manipulador de eventos para a janela Loaded eventos e anexa um manipulador de eventos para o controle OnButtonClick de evento.

Em MainWindow.xaml.vb ou MainWindow.xaml.cs, adicione o seguinte código para o MainWindow classe.

Private app As Application
Private myWindow As Window
Private initFontWeight As FontWeight
Private initFontSize As [Double]
Private initFontStyle As FontStyle
Private initBackBrush As SolidColorBrush
Private initForeBrush As SolidColorBrush
Private initFontFamily As FontFamily
Private UIIsReady As Boolean = False


Private Sub Init(ByVal sender As Object, ByVal e As RoutedEventArgs)
    app = System.Windows.Application.Current
    myWindow = CType(app.MainWindow, Window)
    myWindow.SizeToContent = SizeToContent.WidthAndHeight
    wfh.TabIndex = 10
    initFontSize = wfh.FontSize
    initFontWeight = wfh.FontWeight
    initFontFamily = wfh.FontFamily
    initFontStyle = wfh.FontStyle
    initBackBrush = CType(wfh.Background, SolidColorBrush)
    initForeBrush = CType(wfh.Foreground, SolidColorBrush)

    Dim mc As MyControl1 = wfh.Child

    AddHandler mc.OnButtonClick, AddressOf Pane1_OnButtonClick
    UIIsReady = True

End Sub
private Application app;
private Window myWindow;
FontWeight initFontWeight;
Double initFontSize;
FontStyle initFontStyle;
SolidColorBrush initBackBrush;
SolidColorBrush initForeBrush;
FontFamily initFontFamily;
bool UIIsReady = false;

private void Init(object sender, EventArgs e)
{
    app = System.Windows.Application.Current;
    myWindow = (Window)app.MainWindow;
    myWindow.SizeToContent = SizeToContent.WidthAndHeight;
    wfh.TabIndex = 10;
    initFontSize = wfh.FontSize;
    initFontWeight = wfh.FontWeight;
    initFontFamily = wfh.FontFamily;
    initFontStyle = wfh.FontStyle;
    initBackBrush = (SolidColorBrush)wfh.Background;
    initForeBrush = (SolidColorBrush)wfh.Foreground;
    (wfh.Child as MyControl1).OnButtonClick += new MyControl1.MyControlEventHandler(Pane1_OnButtonClick);
    UIIsReady = true;
}

Porque o XAML discutidos adicionada anteriormente MyControl1 para o WindowsFormsHost coleção de elementos filho do elemento, você pode converter o WindowsFormsHost do elemento Child para obter a referência a MyControl1. You can then use that reference to attach an event handler to OnButtonClick.

Além de ser uma referência ao controle em si, WindowsFormsHost expõe várias propriedades do controle, que você pode manipular a partir do aplicativo. The initialization code assigns those values to private global variables for later use in the application.

Para que você pode acessar facilmente os tipos de MyControls DLL, adicione o seguinte Imports ou using à parte superior do arquivo.

Imports MyControls
using MyControls;

Handling the OnButtonClick Event

MyControl1 raises the OnButtonClick event when the user clicks either of the control's buttons.

Add the following code to the MainWindow class.

'Handle button clicks on the Windows Form control
Private Sub Pane1_OnButtonClick(ByVal sender As Object, ByVal args As MyControlEventArgs)
    txtName.Inlines.Clear()
    txtAddress.Inlines.Clear()
    txtCity.Inlines.Clear()
    txtState.Inlines.Clear()
    txtZip.Inlines.Clear()

    If args.IsOK Then
        txtName.Inlines.Add(" " + args.MyName)
        txtAddress.Inlines.Add(" " + args.MyStreetAddress)
        txtCity.Inlines.Add(" " + args.MyCity)
        txtState.Inlines.Add(" " + args.MyState)
        txtZip.Inlines.Add(" " + args.MyZip)
    End If

End Sub
//Handle button clicks on the Windows Form control
private void Pane1_OnButtonClick(object sender, MyControlEventArgs args)
{
    txtName.Inlines.Clear();
    txtAddress.Inlines.Clear();
    txtCity.Inlines.Clear();
    txtState.Inlines.Clear();
    txtZip.Inlines.Clear();

    if (args.IsOK)
    {
        txtName.Inlines.Add( " " + args.MyName );
        txtAddress.Inlines.Add( " " + args.MyStreetAddress );
        txtCity.Inlines.Add( " " + args.MyCity );
        txtState.Inlines.Add( " " + args.MyState );
        txtZip.Inlines.Add( " " + args.MyZip );
    }
}

The data in the text boxes is packed into the MyControlEventArgs object. If the user clicks the OK button, the event handler extracts the data and displays it in the panel below MyControl1.

Modifying the Control’s Properties

The WindowsFormsHost element exposes several of the hosted control's default properties. Como resultado, você pode alterar a aparência do controle para corresponder a mais de perto o estilo do seu aplicativo. The sets of option buttons in the left panel enable the user to modify several color and font properties. Each set of buttons has a handler for the Click event, which detects the user's option button selections and changes the corresponding property on the control.

Add the following code to the MainWindow class.

Private Sub BackColorChanged(ByVal sender As Object, ByVal e As RoutedEventArgs)

    If sender.Equals(rdbtnBackGreen) Then
        wfh.Background = New SolidColorBrush(Colors.LightGreen)
    ElseIf sender.Equals(rdbtnBackSalmon) Then
        wfh.Background = New SolidColorBrush(Colors.LightSalmon)
    ElseIf UIIsReady = True Then
        wfh.Background = initBackBrush
    End If

End Sub

Private Sub ForeColorChanged(ByVal sender As Object, ByVal e As RoutedEventArgs)
    If sender.Equals(rdbtnForeRed) Then
        wfh.Foreground = New SolidColorBrush(Colors.Red)
    ElseIf sender.Equals(rdbtnForeYellow) Then
        wfh.Foreground = New SolidColorBrush(Colors.Yellow)
    ElseIf UIIsReady = True Then
        wfh.Foreground = initForeBrush
    End If

End Sub

Private Sub FontChanged(ByVal sender As Object, ByVal e As RoutedEventArgs)
    If sender.Equals(rdbtnTimes) Then
        wfh.FontFamily = New FontFamily("Times New Roman")
    ElseIf sender.Equals(rdbtnWingdings) Then
        wfh.FontFamily = New FontFamily("Wingdings")
    ElseIf UIIsReady = True Then
        wfh.FontFamily = initFontFamily
    End If

End Sub

Private Sub FontSizeChanged(ByVal sender As Object, ByVal e As RoutedEventArgs)
    If sender.Equals(rdbtnTen) Then
        wfh.FontSize = 10
    ElseIf sender.Equals(rdbtnTwelve) Then
        wfh.FontSize = 12
    ElseIf UIIsReady = True Then
        wfh.FontSize = initFontSize
    End If

End Sub

Private Sub StyleChanged(ByVal sender As Object, ByVal e As RoutedEventArgs)
    If sender.Equals(rdbtnItalic) Then
        wfh.FontStyle = FontStyles.Italic
    ElseIf UIIsReady = True Then
        wfh.FontStyle = initFontStyle
    End If

End Sub

Private Sub WeightChanged(ByVal sender As Object, ByVal e As RoutedEventArgs)
    If sender.Equals(rdbtnBold) Then
        wfh.FontWeight = FontWeights.Bold
    ElseIf UIIsReady = True Then
        wfh.FontWeight = initFontWeight
    End If

End Sub
private void BackColorChanged(object sender, RoutedEventArgs e)
{
    if (sender == rdbtnBackGreen)
        wfh.Background = new SolidColorBrush(Colors.LightGreen);
    else if (sender == rdbtnBackSalmon)
        wfh.Background = new SolidColorBrush(Colors.LightSalmon);
    else if (UIIsReady == true)
        wfh.Background = initBackBrush;
}

private void ForeColorChanged(object sender, RoutedEventArgs e)
{
    if (sender == rdbtnForeRed)
        wfh.Foreground = new SolidColorBrush(Colors.Red);
    else if (sender == rdbtnForeYellow)
        wfh.Foreground = new SolidColorBrush(Colors.Yellow);
    else if (UIIsReady == true)
        wfh.Foreground = initForeBrush;
}

private void FontChanged(object sender, RoutedEventArgs e)
{
    if (sender == rdbtnTimes)
        wfh.FontFamily = new FontFamily("Times New Roman");
    else if (sender == rdbtnWingdings)
        wfh.FontFamily = new FontFamily("Wingdings");
    else if (UIIsReady == true)
        wfh.FontFamily = initFontFamily;
}
private void FontSizeChanged(object sender, RoutedEventArgs e)
{
    if (sender == rdbtnTen)
        wfh.FontSize = 10;
    else if (sender == rdbtnTwelve)
        wfh.FontSize = 12;
    else if (UIIsReady == true)
        wfh.FontSize = initFontSize;
}
private void StyleChanged(object sender, RoutedEventArgs e)
{
    if (sender == rdbtnItalic)
        wfh.FontStyle = FontStyles.Italic;
    else if (UIIsReady == true)
        wfh.FontStyle = initFontStyle;
}
private void WeightChanged(object sender, RoutedEventArgs e)
{
    if (sender == rdbtnBold)
        wfh.FontWeight = FontWeights.Bold;
    else if (UIIsReady == true)
        wfh.FontWeight = initFontWeight;
}

Criar e executar o aplicativo. Adicionar algum texto no controle Windows Forms composto e clique em OK. O texto é exibido nos rótulos. Clique nos botões de rádio diferente para ver o efeito no controle.

Consulte também

Tarefas

Demonstra Passo a passo: Hospedando um controle Windows Forms no WPF

Referência

ElementHost

WindowsFormsHost

Conceitos

Demonstra Passo a passo: Hospedando um controle composto do WPF no Windows Forms

Outros recursos

WPF Designer

Histórico de alterações

Date

History

Motivo

August 2010

Atualizado para 2010 de Visual Studio.

Comentários do cliente.