Поделиться через


Пошаговое руководство. Привязка к данным в гибридных приложениях

Привязка источника данных к элементу управления необходима для предоставления пользователям доступа к базовым данным независимо от используемой системы — Windows Forms или WPF. В данном пошаговом руководстве показано, как можно использовать привязку данных в гибридных приложениях, содержащих элементы управления Windows Forms и WPF.

В этом пошаговом руководстве демонстрируется выполнение следующих задач.

  • Создание проекта.

  • Определение шаблона данных.

  • Указание макета формы.

  • Указание привязки данных.

  • Отображение данных с помощью взаимодействия.

  • Добавление источника данных к проекту.

  • Привязка к источнику данных.

Полный пример кода для задач, приведенных в этом руководстве, см. в разделе Пример привязки данных в гибридных приложениях.

По окончании выполнения этих задач пользователь будет иметь представление о привязке данных в гибридных приложениях.

Обязательные компоненты

Ниже приведены компоненты, необходимые для выполнения данного пошагового руководства.

  • Visual Studio 2010.

  • Доступ к базе данных "Борей" на Microsoft SQL Server.

Создание проекта

Чтобы создать и настроить проект

  1. Создайте проект приложения WPF с именем WPFWithWFAndDatabinding.

  2. В обозревателе решений добавьте ссылки на следующие сборки.

    • WindowsFormsIntegration

    • System.Windows.Forms

  3. Откройте файл MainWindow.xaml в сред. Конструктор WPF.

  4. В элементе Window добавьте следующее сопоставление пространств имен Windows Forms.

    xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
    
  5. Измените имя по умолчанию элемента Grid на mainGrid путем задания свойства Name.

        <Grid x:Name="mainGrid">
    

Определение шаблона данных.

Основной список клиентов отображается в элементе управления ListBox. В следующем примере кода определяется объект DataTemplate с именем ListItemsTemplate, который управляет визуальным деревом элемента управления ListBox. Этот DataTemplate присваивается свойству ItemTemplate элемента управления ListBox.

Чтобы определить шаблон данных

  • Скопируйте следующую разметку XAML в объявление элемента Grid.

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

Задание макета формы.

Макет формы определяется таблицей из трех строк и трех столбцов. Элементы управления Label предоставляются для идентификации каждого столбца в таблице "Клиенты".

Чтобы настроить макет таблицы

  • Скопируйте следующую разметку XAML в объявление элемента Grid.

            <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>
    

Чтобы настроить элементы управления Label

  • Скопируйте следующую разметку XAML в объявление элемента Grid.

            <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>
    

Задание привязки данных.

Основной список клиентов отображается в элементе управления ListBox. Вложенный ListItemsTemplate привязывает элемент управления TextBlock к полю ContactName из базы данных.

Сведения о каждой записи клиента отображаются в нескольких элементах управления TextBox.

Чтобы задать привязку данных

  • Скопируйте следующую разметку XAML в объявление элемента Grid.

    Класс Binding привязывает элемент управления TextBox к соответствующим полям в базе данных.

            <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>
    

Отображение данных с помощью взаимодействия.

Заказы, соответствующие выбранному клиенту, будут отображены в элементе управления System.Windows.Forms.DataGridView с именем dataGridView1. Элемент управления dataGridView1 привязан к источнику данных в файле кода программной части. Элемент управления WindowsFormsHost является родительским для данного элемента управления Windows Forms.

Для отображения данных в элементе управления DataGridView

  • Скопируйте следующую разметку XAML в объявление элемента Grid.

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

Добавление источника данных к проекту.

С помощью Visual Studio можно легко добавить источник данных к проекту. Данная процедура добавляет набор типобезопасных данных в проект. Несколько других классов поддержки, таких как адаптеры таблиц для каждой из выбранных таблиц, также добавляются.

Добавление источника данных

  1. В меню Данные выберите команду Добавить новый источник данных.

  2. В мастере настройки источника данных выберите подключение к базе данных Northwind с использованием набора данных. Дополнительные сведения см. в разделе Практическое руководство. Подключение к данным в базе данных.

  3. В ответ на запрос Мастера настройки источника данных, сохраните строку подключения как NorthwindConnectionString.

  4. После вывода запроса на выбор объектов базы данных, выберите таблицы Customers и Orders и присвойте созданному набору данных имя NorthwindDataSet.

Привязка к источнику данных.

Компонент System.Windows.Forms.BindingSource предоставляет унифицированный интерфейс для источника данных приложения. Привязка к источнику данных реализуется в файле кода программной части.

Чтобы выполнить привязку к источнику данных

  1. Откройте файл кода программной части с именем MainWindow.xaml.vb или MainWindow.xaml.cs.

  2. Скопируйте следующий код в определение класса MainWindow.

    Этот код объявляет компонент BindingSource и связанные вспомогательные классы, которые подключаются к базе данных.

    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. Скопируйте следующий код в конструктор.

    Этот код создает и инициализирует компонент BindingSource.

    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. Откройте файл MainWindow.xaml.

  5. В представлении конструирования или представлении XAML выберите элемент Window.

  6. В окне свойств перейдите на вкладку События.

  7. Дважды щелкните событие Loaded.

  8. Скопируйте следующий код в обработчик событий Loaded.

    Этот код назначает компонент BindingSource в качестве контекста данных и заполняет объекты адаптера Customers и Orders.

    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. Скопируйте следующий код в определение класса MainWindow.

    Этот метод обрабатывает событие CurrentChanged и обновляет текущий элемент привязки данных.

    ' 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. Нажмите клавишу F5 для построения и запуска приложения.

См. также

Ссылки

ElementHost

WindowsFormsHost

Основные понятия

Пошаговое руководство. Размещение составного элемента управления Windows Forms в приложении WPF

Пошаговое руководство. Размещение составного элемента управления WPF в форме Windows Forms

Другие ресурсы

Конструктор WPF

Data Binding in Hybrid Applications Sample

Журнал изменений

Дата

Журнал

Причина

Август 2010 г.

Обновлено для Visual Studio 2010.

Обратная связь от клиента.