我知道有很多关于数据绑定(bind)组合框的问题,也有很多教程,但我觉得这些教程很难。所以我才问这个问题。
假设我的数据库中有两个表:
客户
CustomerID
Name
GenderID
性别类型
GenderTypeID
GenderType
我使用 ADO.Net 实体数据模型创建了模型。因此,我正在使用 Entity Framework 。
现在我有一个 ViewModel,其中声明了一个名为 Customers 的属性,如下所示:
private List<Customer> _customers;
public List<Customer> Customers
{
get
{
return _customers;
}
set
{
_customers = value;
OnPropertyChanged("Customers");
}
}
现在我有一个像这样的 View :
<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>
我不知道如何绑定(bind)组合框,以便我可以将男性和女性视为组合框的项目,当我选择时,我应该获得相应的 GenderID 而不是 GenderType。
我知道这是一个非常简单直接的问题,但我对 WPF 非常陌生,并且正在尝试学习它。
最佳答案
试试这个:
<ComboBox
<!--ItemsSource bound to property of type collection of GenderTypes, containing all gender types you have -->
ItemsSource="{Binding MyGenderTypes}"
<!--Tell comboBox to display GenderType property of selected GenderTypes-->
DisplayMemberPath="GenderType"
<!--Tell comboBox that the SelectedValue should be GenderID property of selected GenderTypes-->
SelectedValuePath="GenderID"
<!--SelectedValue bound to property of type int (the same type of GenderID)-->
SelectedValue="{Binding SelectedGenderID, Mode=TwoWay}" />
您将看到显示 GenderType 的组合框,但所选值将是相应的 GenderID。如你所愿...
关于c# - 如何在 WPF MVVM 中将组合框与外键绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20509957/