Пошаговое руководство. Привязка к данным в гибридных приложениях
Обновлен: Ноябрь 2007
Привязка источника данных к элементу управления необходима для предоставления пользователям доступа к основным данным независимо от того, используется Windows Forms или WPF. В данном пошаговом руководстве показано, как можно использовать привязку данных в гибридных приложениях, содержащих элементы управления Windows Forms и WPF.
В этом пошаговом руководстве рассматриваются следующие задачи:
Создание проекта.
Определение шаблона данных.
Указание макета формы.
Указание привязки данных.
Отображение данных с помощью взаимодействия.
Добавление источника данных к проекту.
Привязка к источнику данных.
Полный пример кода задач, приведенных в этом пошаговом руководстве, см. в разделе Пример привязки данных в гибридном приложении.
По окончании выполнения этих задач пользователь будет иметь представление о привязке данных в гибридных приложениях.
![]() |
---|
Отображаемые диалоговые окна и команды меню могут отличаться от описанных в справке в зависимости от текущих параметров и выпуска. Чтобы изменить параметры, выберите в меню Сервис команду Импорт и экспорт параметров. Дополнительные сведения см. в разделе Параметры Visual Studio. |
Обязательные компоненты
Для выполнения инструкций данного пошагового руководства необходимы следующие компоненты:
Visual Studio 2008.
Доступ к базе данных «Борей» на Microsoft SQL Server.
Создание проекта
Чтобы создать и настроить проект
Создайте проект приложения WPF с именем WPFWithWFAndDatabinding.
В обозревателе решений добавьте ссылку на сборку WindowsFormsIntegration с именем WindowsFormsIntegration.dll.
В обозревателе решений добавьте ссылку на сборку Windows Forms с именем System.Windows.Forms.dll.
Откройте файл Window1.xaml в конструкторе WPF (конструктор).
В начале файла добавьте пространства имен Windows Forms со следующим кодом.
<Window x:Class="Window1" xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms" Title="WPFWithWFAndDatabinding" Loaded="WindowLoaded" >
<Window x:Class="WPFWithWFAndDatabinding.Window1" xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms" Title="WPFWithWFAndDatabinding" Loaded="WindowLoaded" >
Измените имя по умолчанию элемента Grid на mainGrid путем задания свойства Name.
<Grid x:Name="mainGrid">
<Grid x:Name="mainGrid">
Определение шаблона данных.
Основной список клиентов отображается в элементе управления ListBox. В следующем примере кода определяется объект DataTemplate с именем ListItemsTemplate, который управляет визуальным деревом элемента управления ListBox. Этот DataTemplate присваивается свойству ItemTemplate элемента управления ListBox.
Чтобы определить шаблон данных
Скопируйте следующий код в объявление элемента Grid.
<Grid.Resources> <DataTemplate x:Key="ListItemsTemplate"> <TextBlock Text="{Binding Path=ContactName}"/> </DataTemplate> </Grid.Resources>
<Grid.Resources> <DataTemplate x:Key="ListItemsTemplate"> <TextBlock Text="{Binding Path=ContactName}"/> </DataTemplate> </Grid.Resources>
Задание макета формы.
Макет формы определяется таблицей из трех строк и трех столбцов. Элементы управления Label предоставляются для идентификации каждого столбца в таблице «Клиенты».
Чтобы настроить макет таблицы
Скопируйте следующий код в объявление элемента 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>
<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
Скопируйте следующий код в объявление элемента 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>
<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.
Чтобы задать привязку данных
Скопируйте следующий код в объявление элемента 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>
<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
Скопируйте следующий код в объявление элемента Grid.
<WindowsFormsHost Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" Margin="20,5,5,5" Height="300"> <wf:DataGridView x:Name="dataGridView1"/> </WindowsFormsHost>
<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 можно легко добавить источник данных к проекту. Данная процедура добавляет набор строго типизированных данных в проект. Несколько других классов поддержки, таких как адаптеры таблиц для каждой из выбранных таблиц, также добавляются.
Чтобы добавить источник данных
В меню Проект выберите пункт Добавить новый источник данных….
В Мастере настройки источника данных выберите Новое подключение для создания подключения к базе данных «Борей». Дополнительные сведения см. в разделе Практическое руководство. Подключение к данным в базе данных.
В ответ на запрос Мастера настройки источника данных, сохраните строку подключения как NorthwindConnectionString.
Выберите таблицы «Клиенты» и «Заказы», а присвойте созданному набору данных имя NorthwindDataSet.
Привязка к источнику данных.
Компонент System.Windows.Forms.BindingSource предоставляет унифицированный интерфейс для источника данных приложения. Привязка к источнику данных реализуется в файле кода программной части.
Чтобы выполнить привязку к источнику данных
Откройте файл кода программной части, который называется Window1.xaml.cs или Window1.xaml.vb.
Скопируйте следующий код в определение класса Window1.
Этот код объявляет компонент 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();
Скопируйте следующий код в конструктор Window1 сразу после вызова метода InitializeComponent.
Этот код создает и инициализирует компонент 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 Window1() { 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; }
Скопируйте следующий код в определение класса Window1 сразу после конструктора.
Этот код определяет обработчик событий Loaded, который назначает компонент BindingSource в качестве контекста данных и заполняет объекты адаптера Customers и Orders.
Private Sub WindowLoaded( _ 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 WindowLoaded(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); }
Скопируйте следующий код в определение класса Window1 сразу после метода WindowLoaded.
Этот метод обрабатывает событие 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; }
Нажмите клавишу F5 для построения и запуска приложения.
См. также
Задачи
Пример привязки данных в гибридном приложении
Основные понятия
Обзор: размещение элементов управления Windows Presentation Foundation в приложении Windows Forms