简体   繁体   English

将WPF中的组合框绑定到实体类

[英]Bind Combobox in WPF to Entity class

I have a data input form where i have textboxes,comboboxes and datepickers. 我有一个数据输入表单,其中有文本框,组合框和日期选择器。 I want to Bind comboboxes to the DB column so that users select the correct value for insertion. 我想将组合框绑定到DB列,以便用户选择正确的插入值。 I have attached the viewmodel class and XAML code. 我已经附上了viewmodel类和XAML代码。 In the viewmodel code "private void GetSW()" - this gets all the list of the entity class and "private void addSW()" this adds the record to the DB, Except the combobox binding everything works fine. 在视图模型代码“ private void GetSW()”中,这将获取实体类的所有列表,而“ private void addSW()”会将记录添加至数据库,除了组合框绑定之外,其他方法都可以正常工作。 in XAML i have binded combobox like this but this give blank combobox, please help what i am missing. 在XAML中,我已经像这样绑定了组合框,但这给了空白的组合框,请帮助我所缺少的。 I researched many topics on this forum but didn't find any solution 我在这个论坛上研究了许多主题,但没有找到任何解决方案

<ComboBox x:Name="PSW" Grid.Column="3" Grid.Row="2" ItemsSource="{Binding newSW.PreviousSW}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Height="20"/>

Its a ViewModel Code 它是一个ViewModel代码

using BusinessEntities;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using MUDB.Services;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace MUDB.Ui.Logic
{
    public class SoftwareVersionListViewModel:ViewModelBase
    {
        private bool enableRowDetails=false;
        public bool EnagleRowDetails
        {
            get { return enableRowDetails; }
            set {
                enableRowDetails = value;
                RaisePropertyChanged();
            }
        }



        public SoftwareVersionListViewModel()
        {
            SaveSW = new RelayCommand(addSW);
            //savecommand = new RelayCommand(addprod);
            GetSW();
            newSW = new SoftwareDefEntity();
            EditSW = new RelayCommand(() => {
                EnagleRowDetails = true;

                MessageBox.Show("Edit button clicked!!");});

            //SWList = new SoftwareDefEntity(); //Initializing the object of the Entity class
            }

        public List<SoftwareDefEntity> SWentities
        {
            get;
            set;
        }



        private SoftwareDefEntity _selectedsw;
        public SoftwareDefEntity Selectedsw
        {
            get { return _selectedsw; }
            set
            {
                _selectedsw = value; //This will get all the values of that particular Selected row that are defined in the entity class
                EnagleRowDetails = false; //Reset boolean value EnagleRowDetails, so that the selected rowdetails are disabled until Edit button is not clicked.
                //ShowView();
            }
        }

        public RelayCommand SaveSW { get; private set; }
        public RelayCommand EditSW { get; private set; }
        public SoftwareDefEntity newSW { get; private set; }


        private void ShowView()
        {
            //cUSTOM METHODS
        }

        private void GetSW() // Method that reads the data from the service layer
        {
            SWDefService obj = new SWDefService();
            SWentities = obj.getSW() ; //getSW is the method refered in Service layer

        }

        private void addSW()
        {
            SWDefService obj = new SWDefService();
            obj.addSW(newSW); //newproduct object will hold the value of the binded control, in XAML its binded like this "{Binding newproduct.ProductName(ProductName is the field name in the entityclass/DB table)}" 
            newSW = new SoftwareDefEntity();

        }
    }


}

This is the XAML Code 这是XAML代码

<UserControl x:Class="MUDB.Ui.CreateSW"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:MUDB.Ui"
             xmlns:converter="clr-namespace:MUDB.Ui.Logic.Converters;assembly=MUDB.Ui.Logic"
             xmlns:enums="clr-namespace:MUDB.Ui.Logic.Enums;assembly=MUDB.Ui.Logic"
             mc:Ignorable="d" Height="Auto" Width="Auto"
            DataContext="{Binding SoftwareVersionList,Source={StaticResource Locator}}" >
    <UserControl.Resources>
        <converter:RadioButtonToBooleanConverter x:Key="RadioButtonToBooleanConverter" />
    </UserControl.Resources>
    <Grid>
        <Border Background="#90000000" Visibility="{Binding Visibility}">
            <Border BorderBrush="Black" BorderThickness="1" Background="White" 
                    CornerRadius="10,0,10,0" VerticalAlignment="Center"
                    HorizontalAlignment="Center">
                <Border.BitmapEffect>
                    <DropShadowBitmapEffect Color="Black" Opacity="0.5" Direction="270" ShadowDepth="0.7" />
                </Border.BitmapEffect> 
                <Grid Margin="10">

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="200"/>
            <ColumnDefinition Width="Auto"/>

        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="40"/>
            <RowDefinition Height="25"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="25"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="25"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="100"/>
            <RowDefinition Height="40"/>
            <RowDefinition Height="40"/>
            <RowDefinition Height="40"/>
        </Grid.RowDefinitions>

        <Label Content="Create New Software Version" Grid.Column="0" Grid.Row="0" Foreground="White" Background="black"
               HorizontalAlignment="Stretch" VerticalAlignment="Center" Grid.ColumnSpan="3" />
        <Label Content="ECU" Grid.Column="0" Grid.Row="1" Foreground="Black" HorizontalAlignment="Left"
               VerticalAlignment="Bottom" />
        <Label Content="Software Name" Grid.Column="1" Grid.Row="1" Foreground="Black" HorizontalAlignment="Left"
               VerticalAlignment="Bottom" />
        <Label Content="Previous Software" Grid.Column="2" Grid.Row="1" Foreground="Black" HorizontalAlignment="Left"
               VerticalAlignment="Bottom" />
        <Label Content="Request Freeze Date" Grid.Column="0" Grid.Row="3" Foreground="Black" HorizontalAlignment="Left"
               VerticalAlignment="Bottom" />
        <Label Content="Request Freeze Status" Grid.Column="1" Grid.Row="3" Foreground="Black" HorizontalAlignment="Left"
               VerticalAlignment="Bottom" />
        <Label Content="Software Freeze Date" Grid.Column="0" Grid.Row="5" Foreground="Black" HorizontalAlignment="Left"
               VerticalAlignment="Center" />
        <Label Content="Software Freeze Status" Grid.Column="1" Grid.Row="5" Foreground="Black" HorizontalAlignment="Left"
               VerticalAlignment="Center" />
        <Label Content="Comments" Grid.Column="0" Grid.Row="7" Foreground="Black" HorizontalAlignment="Left"
               VerticalAlignment="Center" />
                    <ComboBox x:Name="ECU" Grid.Column="0" Grid.Row="2" Text="{Binding newSW.ECU}" Margin="10 0 0 0" HorizontalAlignment="Left" VerticalAlignment="Top" Width="80" Height="Auto">
                        <ComboBoxItem Name="cbi1">ACM</ComboBoxItem>
                        <ComboBoxItem Name="cbi2">MCM</ComboBoxItem>
                    </ComboBox>
                    <TextBox x:Name="SW" Grid.Column="1" Grid.Row="2" Text="{Binding newSW.SoftwareName}" HorizontalAlignment="Left" VerticalAlignment="Top"  Height="Auto" Width="150"  />
                    <ComboBox x:Name="PSW" Grid.Column="3" Grid.Row="2" ItemsSource="{Binding PreviousSW}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Height="20"/>
                    <DatePicker Grid.Column="0" Grid.Row="4" Margin="10 0 0 0" HorizontalAlignment="Left" VerticalAlignment="top" SelectedDate="{Binding newSW.Req_Freeze_Date}" Height="Auto" Width="Auto"/>
                    <DatePicker Grid.Column="0" Grid.Row="6" Margin="10 0 0 0" HorizontalAlignment="Left" VerticalAlignment="top" SelectedDate="{Binding newSW.SW_Freeze_Date}" Height="Auto" Width="Auto"/>
                    <RadioButton Content="Yes" GroupName="ReQstat" IsChecked="{Binding newSW.Req_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.Yes}}" Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="4"  HorizontalAlignment="Left"  VerticalAlignment="Top" Height="14" Width="Auto"/>
                    <RadioButton Content="No" GroupName="ReQstat"  IsChecked="{Binding newSW.Req_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.No}}" Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="4" Margin="60 0 0 0" HorizontalAlignment="Left"  VerticalAlignment="Top" Height="Auto" Width="Auto"/>
                    <RadioButton Content="Yes" GroupName="SWstat" IsChecked="{Binding newSW.SW_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.Yes}}"   Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="6"  HorizontalAlignment="Left"  VerticalAlignment="Top" Height="Auto" Width="Auto"/>
                    <RadioButton Content="No" GroupName="SWstat" IsChecked="{Binding newSW.SW_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.No}}"  Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="6" Margin="60 0 0 0" HorizontalAlignment="Left"  VerticalAlignment="Top" Height="Auto" Width="Auto"/>
                    <TextBox x:Name="CommenttextBox" Grid.Column="1" Grid.Row="7"  HorizontalAlignment="Left" Height="69" TextWrapping="WrapWithOverflow" VerticalAlignment="Center" Text="{Binding Comment}" Width="170" Margin="4.4,2.2,0,0" />
                    <UniformGrid Grid.Row="9" Margin="2" Columns="2" HorizontalAlignment="Stretch"
                                 VerticalAlignment="Center" Height="Auto">
                        <Button x:Name="SaveButton" Command="{Binding SaveSW}" Content="Save"  Height="27"   />
                        <Button x:Name="CloseButton" Click="CloseButton_Click" Content="Close" Height="26"  />
                    </UniformGrid>
                </Grid>
            </Border>
        </Border>
    </Grid>
</UserControl>

I guess you want to display the list of SoftwareDefEntity objects in your ComboBox . 我猜您想在ComboBox显示SoftwareDefEntity对象的列表。

Bind to the SWentities property then: 然后绑定到SWentities属性:

<ComboBox x:Name="PSW" Grid.Column="3" Grid.Row="2" ItemsSource="{Binding SWentities}" DisplayMemberPath="Name" ... />

And raise the PropertyChanged event in its setter of this property: 并在此属性的设置方法中引发PropertyChanged事件:

private List<SoftwareDefEntity> _swEntities;
public List<SoftwareDefEntity> SWentities
{
    get { return _swEntities; }
    set { _swEntities = value; RaisePropertyChanged(); }
}

This is the code to bind the data to combobox. 这是将数据绑定到组合框的代码。 i did not add any of other controls since those are working fine at your place. 我没有添加任何其他控件,因为这些控件在您的位置正常工作。 Observable collection is easy way to bind combobox . 可观察的集合是绑定组合框的简便方法。

Here is your View Model.. 这是您的视图模型。

 public class SoftwareVersionListViewModel : ViewModelBase
    {
        public SoftwareVersionListViewModel()
        {
            GetSW();
        }

        //Define the observable collection
        private ObservableCollection<SoftwareDefEntity> _SWmappings2 = new ObservableCollection<SoftwareDefEntity>();

        //here is  your Entity list
        public List<SoftwareDefEntity> SWentities
        {
            get;
            set;
        }

        // Obeservable collection property for access
        public ObservableCollection<SoftwareDefEntity> SWmappings2
        {
            get { return _SWmappings2; }
            set
            {
                _SWmappings2 = value;
                OnPropertyChanged("appeventmappings2");
            }
        }

        /// <summary>
        ///  load the combobox
        /// </summary>
       private void GetSW() // Method that reads the data from the service layer
        {
        SWDefService obj = new SWDefService();
        SWentities = obj.getSW(); //getSW is the method refered in Service layer
        SWentities.ForEach(_SWmappings2.Add);
        }
    }

and Xaml... 和Xaml ...

 <ComboBox x:Name="ComboBox"   ItemsSource="{Binding SWmappings2, UpdateSourceTrigger=PropertyChanged}"  DisplayMemberPath="PreviousSW" SelectedItem="{Binding PreviousSW, Mode=TwoWay}"   Grid.Row="0"  >          
 </ComboBox>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM