簡體   English   中英

將WPF中的組合框綁定到實體類

[英]Bind Combobox in WPF to Entity class

我有一個數據輸入表單,其中有文本框,組合框和日期選擇器。 我想將組合框綁定到DB列,以便用戶選擇正確的插入值。 我已經附上了viewmodel類和XAML代碼。 在視圖模型代碼“ private void GetSW()”中,這將獲取實體類的所有列表,而“ private void addSW()”會將記錄添加至數據庫,除了組合框綁定之外,其他方法都可以正常工作。 在XAML中,我已經像這樣綁定了組合框,但這給了空白的組合框,請幫助我所缺少的。 我在這個論壇上研究了許多主題,但沒有找到任何解決方案

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

它是一個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();

        }
    }


}

這是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>

我猜您想在ComboBox顯示SoftwareDefEntity對象的列表。

然后綁定到SWentities屬性:

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

並在此屬性的設置方法中引發PropertyChanged事件:

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

這是將數據綁定到組合框的代碼。 我沒有添加任何其他控件,因為這些控件在您的位置正常工作。 可觀察的集合是綁定組合框的簡便方法。

這是您的視圖模型。

 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);
        }
    }

和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