【发布时间】:2010-10-29 15:05:12
【问题描述】:
好的,所以我对 WPF 和数据绑定还很陌生,但我已经搜索和搜索,似乎无法找到答案。
我有一个数据库(称为 Inventory)和一个数据集(称为 DevicesDataSet)。我要做的是将数据集绑定到列表框,以便可以从 DevicesDataSet 的 Devices 表中选择特定设备,并将其属性显示在 TextBox 中进行编辑。
以下是我目前拥有的 XAML:
<Window x:Class="Inventory.SignOutDevice"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="SignOutDevice" Height="339" Width="392" xmlns:my="clr-namespace:Inventory" Loaded="Window_Loaded">
<Window.Resources>
<my:DevicesDataSet x:Key="devicesDataSet" />
<CollectionViewSource x:Key="devicesViewSource" Source="{Binding Path=Devices, Source={StaticResource devicesDataSet}}" />
</Window.Resources>
<Grid DataContext="{StaticResource devicesViewSource}">
<ListBox Height="237" HorizontalAlignment="Left" Margin="12,12,0,0" Name="listBox1"
VerticalAlignment="Top" Width="254" ItemsSource="{Binding}" SelectedValuePath="Selected">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Make}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBox Margin="223,267,0,0" Text="{Binding Path=Make, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
只要选择了一个设备并编辑了一个属性(我现在只显示一个属性),列表框就会更新,但数据集(数据库?)似乎没有。也就是说,当我离开表单然后再回到它时,列表框会恢复到原来的状态。
所以我想问题是:如何使这些更改持久化/写入数据库?
编辑:Derp,这是更新后的后端 C#:
using System.Windows;
using System.Data;
namespace Inventory
{
public partial class SignOutDevice : Window
{
DevicesDataSet devicesDataSet = null;
Inventory.DevicesDataSetTableAdapters.DevicesTableAdapter devicesDataSetDevicesTableAdapter = null;
public SignOutDevice()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
devicesDataSet = ((Inventory.DevicesDataSet)(this.FindResource("devicesDataSet")));
devicesDataSetDevicesTableAdapter = new Inventory.DevicesDataSetTableAdapters.DevicesTableAdapter();
devicesDataSetDevicesTableAdapter.Fill(devicesDataSet.Devices);
System.Windows.Data.CollectionViewSource devicesViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("devicesViewSource")));
devicesViewSource.View.MoveCurrentToFirst();
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
devicesDataSet.AcceptChanges();
devicesDataSetDevicesTableAdapter.Update(devicesDataSet.Tables["Devices"].Select(null, null, DataViewRowState.Deleted));
devicesDataSetDevicesTableAdapter.Update(devicesDataSet.Tables["Devices"].Select(null, null, DataViewRowState.ModifiedCurrent));
devicesDataSetDevicesTableAdapter.Update(devicesDataSet.Tables["Devices"].Select(null, null, DataViewRowState.Added));
}
}
}
【问题讨论】: