如何在 WPF MVVM 中使用外键绑定组合框

Khu*_*shi 3 c# silverlight wpf xaml mvvm

我知道有很多关于 DataBinding 组合框的问题,也有很多教程,但我觉得这些教程很难。所以,我问这个问题。

假设我的数据库中有两个表:

顾客

CustomerID
Name
GenderID
Run Code Online (Sandbox Code Playgroud)

性别类型

GenderTypeID
GenderType
Run Code Online (Sandbox Code Playgroud)

我已经使用 ADO.Net 实体数据模型创建了我的模型。所以,我正在使用实体框架。

现在我有一个 ViewModel,我在其中声明了一个名为 Customers 的属性,如下所示:

private List<Customer> _customers;
public List<Customer> Customers
{
    get
    {
        return _customers;
    }
    set
    {
        _customers = value;
        OnPropertyChanged("Customers");
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我有一个这样的视图:

<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>
Run Code Online (Sandbox Code Playgroud)

我不知道如何绑定组合框,这样我就可以看到男性和女性作为组合框的项目,当我选择时,我应该得到相应的 GenderID 而不是 GenderType。

我知道这是一个非常简单和直接的问题,但我对 WPF 非常陌生并试图学习它。

har*_*r07 5

尝试这个:

<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}" />
Run Code Online (Sandbox Code Playgroud)

您将获得显示 GenderType 的组合框,但所选值将是相应的 GenderID。就如你所愿...