我正试图弄清楚WPF与SQLite的绑定。
我生成了一个ADO.NET实体数据模型来表示我的SQLite数据库。数据库只保存一个表“People”,其中包含两列“person_id”和“person_name”。现在,我在WPF应用程序中为该表生成了EDM类。
我正在尝试绑定到列表框。我可以从源中删除项目并查看它更新列表框。但我无法使用文本框向源添加项目并查看它更新列表框。
我在Window1类中声明了数据实体,如下所示:
private static MyNewSqliteDbEntities2 _myEntities = new MyNewSqliteDbEntities2();
我有一个列表框,它绑定到Window_Loaded事件处理程序中的ObjectQuery,如下所示:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
peopleListBox.ItemsSource = _myEntities.People;
}
我有另一个文本框,用于通过单击按钮添加人员。我可以通过选择列表框中的项目并单击删除按钮来删除项目。单击提交按钮时,更改将提交到数据库。请考虑以下代码:
private void addButton_Click(object sender, RoutedEventArgs e)
{
if (addPersonTextBox.Text != "")
{
People newPerson = new People();
newPerson.person_name = addPersonTextBox.Text;
//_myEntities.AddToPeople(newPerson);
_myEntities.AddObject("People", newPerson);
addPersonTextBox.Text = "";
}
}
private void deleteButton_Click(object sender, RoutedEventArgs e)
{
_myEntities.DeleteObject(peopleListBox.SelectedItem);
}
private void commitButton_Click(object sender, RoutedEventArgs e)
{
_myEntities.SaveChanges();
}
我尝试使用另一个名为“Refresh”的按钮以下列方式刷新列表框控件,但没有运气(尽管,当我单步执行代码时,我看到源代码已更新):
private void refreshButton_Click(object sender, RoutedEventArgs e)
{
peopleListBox.ItemsSource = null;
peopleListBox.ItemsSource = _myEntities.People;
}
如果您想知道,这是XAML代码:
<Window x:Class="BindingToSqLite.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="400" Width="400" Loaded="Window_Loaded">
<Window.Resources>
<DataTemplate x:Key="personNameTemplate">
<TextBlock Text="{Binding Path=person_name}"/>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="190*" />
<ColumnDefinition Width="94*" />
<ColumnDefinition Width="94*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="182*" />
<RowDefinition Height="38*" />
<RowDefinition Height="38*" />
<RowDefinition Height="32*" />
</Grid.RowDefinitions>
<ListBox Margin="5" Name="peopleListBox" Grid.ColumnSpan="3" ItemTemplate="{StaticResource personNameTemplate}" />
<TextBox Grid.Row="1" Grid.ColumnSpan="2" Margin="5,10" Name="addPersonTextBox" />
<Button Grid.Column="2" Grid.Row="1" Margin="5" Name="addButton" Click="addButton_Click">Add</Button>
<Button Grid.Row="2" Margin="5" Name="commitButton" Click="commitButton_Click">Commit</Button>
<Button Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="2" Margin="5" Name="deleteButton" Click="deleteButton_Click">Delete</Button>
<Button Grid.Row="3" Margin="5" Name="refreshButton" Click="refreshButton_Click">Refresh</Button>
</Grid>
</Window>
我不确定我是否完全错了。任何帮助表示赞赏。