How to bind a combobox with Foreign Key in WPF MVVM

前端 未结 2 785
旧时难觅i
旧时难觅i 2021-01-06 14:02

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.

相关标签:
2条回答
  • 2021-01-06 14:36

    Add Genders in ViewModel class

    public List<GenderTypes> Genders
            {
                get
                {
                    return _genders;
                }
                set
                {
                    _genders = value;
                    OnPropertyChanged("Genders");
                }
            }
    

    After use like this.

    <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>
    
    0 讨论(0)
  • 2021-01-06 14:55

    Try this:

    <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}" />
    

    You will get the combobox displaying GenderType, but the selected value will be the corresponding GenderID. Just as you wish...

    0 讨论(0)
提交回复
热议问题