c# - 如何在 WPF MVVM 中将组合框与外键绑定(bind)

标签 c# wpf silverlight xaml mvvm

我知道有很多关于数据绑定(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/

相关文章:

c# - 来自 Request.Url.ToString() 的字符串在操作/比较第一个字符时神秘地更改为另一个字符串

c# - 在 Visual Studio 属性面板上禁用属性

c# - IsDirty 比较的集合快照

wpf - 当已选择行时,WPF MVVM DataGrid DoubleClick不起作用

c# - 使用 Silverlight 和 C# 将字节数组转换为列表<byte>

c# - ASP.NET Core 如何执行 Linux shell 命令?

c# - 更新 IQueryable 对象中的值

c# - 遵循 MVVM 在 WPF 应用程序中集成上下文相关帮助

.net - Silverlight 4 RelativeSource FindAncestor 绑定(bind)

visual-studio-2010 - 无法在 Visual Studio 2010 SP1 上安装 silverlight 4 工具