如何在 WPF MVVM 中使用外键绑定组合框 [英] How to bind a combobox with Foreign Key in WPF MVVM
问题描述
我知道关于组合框的数据绑定有很多问题,也有很多教程,但我觉得这些教程很难.所以,我问这个问题.
I know that there are many questions regarding DataBinding a combobox and also there are many tutorials but I feel those tutorials hard. So, I am asking this question.
假设我的数据库中有两个表:
Suppose I have two tables in my database:
客户
CustomerID
Name
GenderID
性别类型
GenderTypeID
GenderType
我使用 ADO.Net 实体数据模型创建了我的模型.所以,我正在使用实体框架.
I have created my models using ADO.Net Entity Data Model. So, I am using Entity Framework.
现在我有一个 ViewModel,我在其中声明了一个名为 Customers 的属性,如下所示:
Now I have a ViewModel in which I declare a property called Customers as below:
private List<Customer> _customers;
public List<Customer> Customers
{
get
{
return _customers;
}
set
{
_customers = value;
OnPropertyChanged("Customers");
}
}
现在我有一个这样的视图:
Now I have a View Like this:
<Window ......>
<Window.DataContext>
<vm:MainWindowViewModel />
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
..
..
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
..
..
</Grid.ColumnDefinitions>
<TextBlock Text="Name" ....../>
<TextBox Text="{Binding Name}"...../>
<TextBlock Text="Gender" ....../>
<TextBox ItemsSource="????"
SelectedValue="????"
SelectedValuePath="????"...../>
</Grid>
</Window>
我不知道如何绑定combobox,所以我可以看到Male和Female作为combobox的项目,当我选择时我应该得到对应的GenderID而不是GenderType.
I dont know how to bind the combobox, so that I can see Male and Female as the items of combobox and when I select I should get corresponding GenderID instead of GenderType.
我知道这是一个非常简单直接的问题,但我对 WPF 非常陌生并正在努力学习它.
I know this is a very simple and straight forward question but I am very much new to WPF and trying to learn it.
推荐答案
在ViewModel类中添加Genders
Add Genders
in ViewModel class
public List<GenderTypes> Genders
{
get
{
return _genders;
}
set
{
_genders = value;
OnPropertyChanged("Genders");
}
}
这样使用后.
<ListBox ItemsSource="{Binding Customers}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="Name" />
<TextBox Text="{Binding Name}" />
<TextBlock Text="Gender" />
<ComboBox ItemsSource="{Binding Genders,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}" DisplayMemberPath="GenderType" SelectedValue="{Binding GenderID}" SelectedValuePath="GenderTypeID"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
这篇关于如何在 WPF MVVM 中使用外键绑定组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!