Demonstra Passo a passo: Vinculação de dados em aplicativos híbridos

Atualização: August 2010

Vincular a uma fonte de dados a um controle é essencial para fornecer aos usuários acesso aos dados subjacentes, se você estiver usando o Windows Forms ou WPF. This walkthrough shows how you can use data binding in hybrid applications that include both Windows Forms and WPF controls.

Tasks illustrated in this walkthrough include:

  • Creating the project.

  • Defining the data template.

  • Specifying the form layout.

  • Specifying data bindings.

  • Displaying data by using interoperation.

  • Adding the data source to the project.

  • Binding to the data source.

Para obter uma listagem de código completo das tarefas ilustradas nesta explicação, consulte A ligação de dados híbrido de exemplo de aplicativos.

When you are finished, you will have an understanding of data binding features in hybrid applications.

Pré-requisitos

You need the following components to complete this walkthrough:

  • Visual Studio 2010.

  • Access to the Northwind sample database running on Microsoft SQL Server.

Creating the Project

To create and set up the project

  1. Create a WPF Application project named WPFWithWFAndDatabinding.

  2. No Solution Explorer, adicione referências aos assemblies seguintes.

    • WindowsFormsIntegration

    • System.Windows.Forms

  3. Abrir MainWindow. XAML na WPF Designer.

  4. No Window elemento, adicione o seguinte Windows Forms mapeamento de namespaces.

    xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
    
  5. Name the default Grid element mainGrid by assigning the Name property.

        <Grid x:Name="mainGrid">
    

Defining the Data Template

The master list of customers is displayed in a ListBox control. The following code example defines a DataTemplate object named ListItemsTemplate that controls the visual tree of the ListBox control. This DataTemplate is assigned to the ListBox control's ItemTemplate property.

To define the data template

  • Copie o seguinte XAML para o Grid de declaração. do elemento

            <Grid.Resources>
                <DataTemplate x:Key="ListItemsTemplate">
                    <TextBlock Text="{Binding Path=ContactName}"/>
                </DataTemplate>
            </Grid.Resources>
    

Specifying the Form Layout

O layout do formulário é definido por uma grade com três linhas e três colunas. Labelcontroles são fornecidos para identificar cada coluna na tabela clientes.

To set up the Grid layout

  • Copie o seguinte XAML para o Grid de declaração. do elemento

            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
    
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
    

To set up the Label controls

  • Copie o seguinte XAML para o Grid de declaração. do elemento

            <StackPanel Orientation="Vertical" Grid.Row="0" Grid.Column="1">
                <Label Margin="20,38,5,2">First Name:</Label>
                <Label Margin="20,0,5,2">Company Name:</Label>
                <Label Margin="20,0,5,2">Phone:</Label>
                <Label Margin="20,0,5,2">Address:</Label>
                <Label Margin="20,0,5,2">City:</Label>
                <Label Margin="20,0,5,2">Region:</Label>
                <Label Margin="20,0,5,2">Postal Code:</Label>
            </StackPanel>
    

Specifying Data Bindings

The master list of customers is displayed in a ListBox control. The attached ListItemsTemplate binds a TextBlock control to the ContactName field from the database.

The details of each customer record are displayed in several TextBox controls.

To specify data bindings

  • Copie o seguinte XAML para o Grid de declaração. do elemento

    The Binding class binds the TextBox controls to the appropriate fields in the database.

            <StackPanel Orientation="Vertical" Grid.Row="0" Grid.Column="0">
                <Label Margin="20,5,5,0">List of Customers:</Label>
                <ListBox x:Name="listBox1" Height="200" Width="200" HorizontalAlignment="Left" 
                   ItemTemplate="{StaticResource ListItemsTemplate}" IsSynchronizedWithCurrentItem="True" Margin="20,5,5,5"/>
            </StackPanel>
    
            <StackPanel Orientation="Vertical" Grid.Row="0" Grid.Column="2">
                <TextBox Margin="5,38,5,2" Width="200" Text="{Binding Path=ContactName}"/>
                <TextBox Margin="5,0,5,2" Width="200" Text="{Binding Path=CompanyName}"/>
                <TextBox Margin="5,0,5,2" Width="200" Text="{Binding Path=Phone}"/>
                <TextBox Margin="5,0,5,2" Width="200" Text="{Binding Path=Address}"/>
                <TextBox Margin="5,0,5,2" Width="200" Text="{Binding Path=City}"/>
                <TextBox Margin="5,0,5,2" Width="30" HorizontalAlignment="Left" Text="{Binding Path=Region}"/>
                <TextBox Margin="5,0,5,2" Width="50" HorizontalAlignment="Left" Text="{Binding Path=PostalCode}"/>
            </StackPanel>
    

Displaying Data by Using Interoperation

The orders corresponding to the selected customer are displayed in a System.Windows.Forms.DataGridView control named dataGridView1. The dataGridView1 control is bound to the data source in the code-behind file. A WindowsFormsHost control is the parent of this Windows Forms control.

To display data in the DataGridView control

  • Copie o seguinte XAML para o Grid de declaração. do elemento

            <WindowsFormsHost Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" Margin="20,5,5,5" Height="300">
                <wf:DataGridView x:Name="dataGridView1"/>
            </WindowsFormsHost>
    

Adding the Data Source to the Project

With Visual Studio, you can easily add a data source to your project. This procedure adds a strongly typed data set to your project. Several other support classes, such as table adapters for each of the chosen tables, are also added.

To add the data source

  1. From the Data menu, select Add New Data Source.

  2. No Data Source Configuration Wizard, criar uma conexão de banco de dados Northwind, usando um dataset. For more information, see Como: Conectar-se a Dados em um Banco de Dados.

  3. When you are prompted by the Data Source Configuration Wizard, save the connection string as NorthwindConnectionString.

  4. Quando for solicitado para escolher seus objetos de banco de dados, selecione o Customers e Orders tabelas e o nome do conjunto de dados gerado NorthwindDataSet.

Binding to the Data Source

The System.Windows.Forms.BindingSource component provides a uniform interface for the application's data source. Binding to the data source is implemented in the code-behind file.

To bind to the data source

  1. Abra o arquivo de code-behind, o que é chamado de MainWindow.xaml.vb ou MainWindow.xaml.cs.

  2. Copy the following code into the MainWindow class definition.

    This code declares the BindingSource component and associated helper classes that connect to the database.

    Private nwBindingSource As System.Windows.Forms.BindingSource
    Private nwDataSet As NorthwindDataSet
    Private customersTableAdapter As New NorthwindDataSetTableAdapters.CustomersTableAdapter()
    Private ordersTableAdapter As New NorthwindDataSetTableAdapters.OrdersTableAdapter()
    
    private System.Windows.Forms.BindingSource nwBindingSource;
    private NorthwindDataSet nwDataSet;
    private NorthwindDataSetTableAdapters.CustomersTableAdapter customersTableAdapter = 
        new NorthwindDataSetTableAdapters.CustomersTableAdapter();
    private NorthwindDataSetTableAdapters.OrdersTableAdapter ordersTableAdapter = 
        new NorthwindDataSetTableAdapters.OrdersTableAdapter();
    
  3. Copie o seguinte código para o construtor.

    This code creates and initializes the BindingSource component.

    Public Sub New()
        InitializeComponent()
    
        ' Create a DataSet for the Customers data.
        Me.nwDataSet = New NorthwindDataSet()
        Me.nwDataSet.DataSetName = "nwDataSet"
    
        ' Create a BindingSource for the Customers data.
        Me.nwBindingSource = New System.Windows.Forms.BindingSource()
        Me.nwBindingSource.DataMember = "Customers"
        Me.nwBindingSource.DataSource = Me.nwDataSet
    
    End Sub
    
    public MainWindow()
    {
        InitializeComponent();
    
        // Create a DataSet for the Customers data.
        this.nwDataSet = new NorthwindDataSet();
        this.nwDataSet.DataSetName = "nwDataSet";
    
        // Create a BindingSource for the Customers data.
        this.nwBindingSource = new System.Windows.Forms.BindingSource();
        this.nwBindingSource.DataMember = "Customers";
        this.nwBindingSource.DataSource = this.nwDataSet;
    }
    
  4. Abra MainWindow. XAML.

  5. No modo de exibição de Design ou XAML, selecione o Window elemento.

  6. Na janela Propriedades, clique na eventos guia.

  7. Clique duas vezes o Loaded de evento.

  8. Copie o seguinte código para o Loaded manipulador de eventos.

    Esse código atribui a BindingSource componente como o contexto de dados e preenche a Customers e Orders objetos do adaptador.

    Private Sub Window_Loaded( _
    ByVal sender As Object, _
    ByVal e As RoutedEventArgs)
    
        ' Fill the Customers table adapter with data.
        Me.customersTableAdapter.ClearBeforeFill = True
        Me.customersTableAdapter.Fill(Me.nwDataSet.Customers)
    
        ' Fill the Orders table adapter with data.
        Me.ordersTableAdapter.Fill(Me.nwDataSet.Orders)
    
        ' Assign the BindingSource to 
        ' the data context of the main grid.
        Me.mainGrid.DataContext = Me.nwBindingSource
    
        ' Assign the BindingSource to 
        ' the data source of the list box.
        Me.listBox1.ItemsSource = Me.nwBindingSource
    
        ' Because this is a master/details form, the DataGridView
        ' requires the foreign key relating the tables.
        Me.dataGridView1.DataSource = Me.nwBindingSource
        Me.dataGridView1.DataMember = "FK_Orders_Customers"
    
        ' Handle the currency management aspect of the data models.
        ' Attach an event handler to detect when the current item 
        ' changes via the WPF ListBox. This event handler synchronizes
        ' the list collection with the BindingSource.
        '
    
        Dim cv As BindingListCollectionView = _
            CollectionViewSource.GetDefaultView(Me.nwBindingSource)
    
        AddHandler cv.CurrentChanged, AddressOf WPF_CurrentChanged
    
    End Sub
    
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        // Fill the Customers table adapter with data.
        this.customersTableAdapter.ClearBeforeFill = true;
        this.customersTableAdapter.Fill(this.nwDataSet.Customers);
    
        // Fill the Orders table adapter with data.
        this.ordersTableAdapter.Fill(this.nwDataSet.Orders);
    
        // Assign the BindingSource to 
        // the data context of the main grid.
        this.mainGrid.DataContext = this.nwBindingSource;
    
        // Assign the BindingSource to 
        // the data source of the list box.
        this.listBox1.ItemsSource = this.nwBindingSource;
    
        // Because this is a master/details form, the DataGridView
        // requires the foreign key relating the tables.
        this.dataGridView1.DataSource = this.nwBindingSource;
        this.dataGridView1.DataMember = "FK_Orders_Customers";
    
        // Handle the currency management aspect of the data models.
        // Attach an event handler to detect when the current item 
        // changes via the WPF ListBox. This event handler synchronizes
        // the list collection with the BindingSource.
        //
    
        BindingListCollectionView cv = CollectionViewSource.GetDefaultView(
            this.nwBindingSource) as BindingListCollectionView;
    
        cv.CurrentChanged += new EventHandler(WPF_CurrentChanged);
    }
    
  9. Copy the following code into the MainWindow class definition.

    This method handles the CurrentChanged event and updates the current item of the data binding.

    ' This event handler updates the current item 
    ' of the data binding.
    Private Sub WPF_CurrentChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim cv As BindingListCollectionView = sender
        Me.nwBindingSource.Position = cv.CurrentPosition
    End Sub
    
    // This event handler updates the current item 
    // of the data binding.
    void WPF_CurrentChanged(object sender, EventArgs e)
    {
        BindingListCollectionView cv = sender as BindingListCollectionView;
        this.nwBindingSource.Position = cv.CurrentPosition;
    }
    
  10. Pressione F5 para criar e executar o aplicativo.

Consulte também

Referência

ElementHost

WindowsFormsHost

Conceitos

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

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

Outros recursos

WPF Designer

Vinculação de dados no exemplo de aplicativos híbrido

Histórico de alterações

Date

History

Motivo

August 2010

Atualizado para 2010 de Visual Studio.

Comentários do cliente.