如何使用MVVM在WPF C#中显示和选择Datagrid ComboBox中的项目

时间:2022-03-03 09:45:36

I want to be able to choose either "true" or "false"(boolean) from a ComboBox that is within a wpf Datagrid and be able to save that choice to my database.

我希望能够从wpf Datagrid中的ComboBox中选择“true”或“false”(boolean),并能够将该选项保存到我的数据库中。

I want to be able to indicate inside of a column if the row is "Active" or not through a boolean variable saved to my database as a bit(1 = true; 0 = false).

我希望能够在列内部指示行是否为“活动”或不通过保存到我的数据库的布尔变量作为位(1 =真; 0 =假)。

Here is my create table statement: Create Table Statement(AccountType)

这是我的create table语句:Create Table Statement(AccountType)

I populate the datagrid using an ObservableCollection as follows:

我使用ObservableCollection填充数据网格,如下所示:

protected override void Get()
{
    using (var dbContext = new IEMASEntitiesDataContext())
    {
        var accountType = from s in dbContext.AccountTypes select s;
        var observable = new  ObservableCollection<AccountType>(accountType);

        Collection = observable;
    }
}

My XAML code is as follows:

我的XAML代码如下:

<DockPanel DataContext="{StaticResource ResourceKey=AccountTypeViewModel}" LastChildFill="True">
    <ToolBar DockPanel.Dock="Top">
        <Button Content="Display"  Command="{Binding GetCommand}" Width="78"/>
        <Button Content="Save" Command="{Binding SaveCommand}" Width="78"/>
    </ToolBar>

    <Grid>
        <GroupBox x:Name="AccountTypeGroupBox">
            <DataGrid x:Name="DataGridAccountType" ItemsSource="{Binding Collection}" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn  Header="AccountType" Width="150" Binding="{Binding Path=AccountTypeName, Mode=TwoWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}"/>
                    <DataGridComboBoxColumn  Header="Active" Width="100" SelectedValueBinding="{Binding StatusList, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="AccountTypeId" DisplayMemberPath="Active"/>                   
                    <DataGridTemplateColumn Width="50" Header="Delete">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Button x:Name="btnDelete" Content="Delete" Command="{Binding DeleteCommand}"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                </DataGrid.Columns>
            </DataGrid>
        </GroupBox>          
    </Grid>
</DockPanel>

It doesn't work. Nothing displays within the comboboxes, and I don't know how to save the selected item to the SQL Server database when it does display. I'd appreciate some help, please. I am using LINQ TO SQL. I am a newbie :-(.

它不起作用。组合框中没有显示任何内容,我不知道如何在显示时将所选项目保存到SQL Server数据库。请给我一些帮助。我正在使用LINQ TO SQL。我是新手:-(。

1 个解决方案

#1


1  

As I can understand the problem is how to bind some XAML resource as a combo ItemsSource and in addtion how to binnd the selected value of a combo to the model behind the DataGrid row. 1. List item:

我可以理解的问题是如何将一些XAML资源绑定为组合ItemsSource,另外如何将组合的选定值绑定到DataGrid行后面的模型。 1.清单项目:

<Window x:Class="SoDataGridProjectsHelpAttempt.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:soDataGridProjectsHelpAttempt="clr-namespace:SoDataGridProjectsHelpAttempt"
    xmlns:system="clr-namespace:System;assembly=mscorlib"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <x:Array x:Key="CountriesArray" Type="soDataGridProjectsHelpAttempt:Country">
        <soDataGridProjectsHelpAttempt:Country CountryName="Germany" CountryPop="150k"/>
        <soDataGridProjectsHelpAttempt:Country CountryName="France" CountryPop="125k"/>
        <soDataGridProjectsHelpAttempt:Country CountryName="Belarus" CountryPop="165k"/>
    </x:Array>
    <x:Array x:Key="StatusArray" Type="soDataGridProjectsHelpAttempt:ActivityStatus">
        <soDataGridProjectsHelpAttempt:ActivityStatus VerbalStatus="Yes" BoolStatus="True"/>
        <soDataGridProjectsHelpAttempt:ActivityStatus VerbalStatus="No" BoolStatus="False"/>
    </x:Array>
</Window.Resources>
<Window.DataContext>
    <soDataGridProjectsHelpAttempt:DataGridMainDataContext/>
</Window.DataContext>
<Grid>
    <DataGrid ItemsSource="{Binding Collection}" AutoGenerateColumns="False" CanUserAddRows="True">
        <DataGrid.Columns>
            <DataGridTextColumn     Width="Auto" Binding="{Binding UName}"/>
            <DataGridComboBoxColumn Header="Country" DisplayMemberPath="CountryName"
                                    ItemsSource="{StaticResource CountriesArray}" Width="Auto"
                                    SelectedItemBinding="{Binding CountryData}"/>
            <!--<DataGridComboBoxColumn Header="ActivityStatus" Width="Auto" ItemsSource="{StaticResource StatusArray}" 
                                    SelectedValueBinding="{Binding IsActive}" SelectedValuePath="BoolStatus" DisplayMemberPath="VerbalStatus"/>-->
            <DataGridComboBoxColumn Header="ActivityStatus" SelectedItemBinding="{Binding IsActive, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
                <DataGridComboBoxColumn.ItemsSource>
                    <x:Array Type="system:Boolean">
                        <system:Boolean>True</system:Boolean>
                        <system:Boolean>False</system:Boolean>
                    </x:Array>
                </DataGridComboBoxColumn.ItemsSource>
            </DataGridComboBoxColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

  1. DataGrid viewmodel:

    DataGrid视图模型:

    public class DataGridMainDataContext
    

    { public DataGridMainDataContext() { Collection = new ObservableCollection(new List { new UserData { UName = "Greg", IsActive = false, }, new UserData { UName = "Joe", IsActive = false, }, new UserData { UName = "Iv", IsActive = false, } });

    {public DataGridMainDataContext(){Collection = new ObservableCollection(new List {new UserData {UName =“Greg”,IsActive = false,},new UserData {UName =“Joe”,IsActive = false,},new UserData {UName =“ Iv“,IsActive = false,}});

    }
    
    public ObservableCollection<UserData> Collection { get; set; }
    

    }

    }

  2. Models: public class UserData : BaseObservableObject { private string _uName; private object _countryData; private bool _isActive;

    模型:公共类UserData:BaseObservableObject {private string _uName;私有对象_countryData;私人布尔_isActive;

    public bool IsActive
    {
        get { return _isActive; }
        set
        {
            _isActive = value;
            OnPropertyChanged();
        }
    }
    
    public string UName
    {
        get { return _uName; }
        set
        {
            _uName = value;
            OnPropertyChanged();
        }
    }
    
    public object CountryData
    {
        get { return _countryData; }
        set
        {
            _countryData = value;
            OnPropertyChanged();
        }
    }
    

    }

    }

    public class ActivityStatus:BaseObservableObject { private bool _boolStatus; private string _verbalStatus;

    public class ActivityStatus:BaseObservableObject {private bool _boolStatus; private string _verbalStatus;

    public bool BoolStatus
    {
        get { return _boolStatus; }
        set
        {
            _boolStatus = value;
            OnPropertyChanged();
        }
    }
    
    public string VerbalStatus
    {
        get { return _verbalStatus; }
        set
        {
            _verbalStatus = value;
            OnPropertyChanged();
        }
    }
    

    }

    }

    public class Country : BaseObservableObject { private string _countryName; private string _countryPop;

    public class国家:BaseObservableObject {private string _countryName; private string _countryPop;

    public string CountryName
    {
        get { return _countryName; }
        set
        {
            _countryName = value;
            OnPropertyChanged();
        }
    }
    
    public string CountryPop
    {
        get { return _countryPop; }
        set
        {
            _countryPop = value;
            OnPropertyChanged();
        }
    }
    
    public Country() { }
    public Country(string n, string d)
    {
        this.CountryName = n;
        this.CountryPop = d;
    }
    

    } Hope it will help you.

    希望它会对你有所帮助。

regards,

问候,

#1


1  

As I can understand the problem is how to bind some XAML resource as a combo ItemsSource and in addtion how to binnd the selected value of a combo to the model behind the DataGrid row. 1. List item:

我可以理解的问题是如何将一些XAML资源绑定为组合ItemsSource,另外如何将组合的选定值绑定到DataGrid行后面的模型。 1.清单项目:

<Window x:Class="SoDataGridProjectsHelpAttempt.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:soDataGridProjectsHelpAttempt="clr-namespace:SoDataGridProjectsHelpAttempt"
    xmlns:system="clr-namespace:System;assembly=mscorlib"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <x:Array x:Key="CountriesArray" Type="soDataGridProjectsHelpAttempt:Country">
        <soDataGridProjectsHelpAttempt:Country CountryName="Germany" CountryPop="150k"/>
        <soDataGridProjectsHelpAttempt:Country CountryName="France" CountryPop="125k"/>
        <soDataGridProjectsHelpAttempt:Country CountryName="Belarus" CountryPop="165k"/>
    </x:Array>
    <x:Array x:Key="StatusArray" Type="soDataGridProjectsHelpAttempt:ActivityStatus">
        <soDataGridProjectsHelpAttempt:ActivityStatus VerbalStatus="Yes" BoolStatus="True"/>
        <soDataGridProjectsHelpAttempt:ActivityStatus VerbalStatus="No" BoolStatus="False"/>
    </x:Array>
</Window.Resources>
<Window.DataContext>
    <soDataGridProjectsHelpAttempt:DataGridMainDataContext/>
</Window.DataContext>
<Grid>
    <DataGrid ItemsSource="{Binding Collection}" AutoGenerateColumns="False" CanUserAddRows="True">
        <DataGrid.Columns>
            <DataGridTextColumn     Width="Auto" Binding="{Binding UName}"/>
            <DataGridComboBoxColumn Header="Country" DisplayMemberPath="CountryName"
                                    ItemsSource="{StaticResource CountriesArray}" Width="Auto"
                                    SelectedItemBinding="{Binding CountryData}"/>
            <!--<DataGridComboBoxColumn Header="ActivityStatus" Width="Auto" ItemsSource="{StaticResource StatusArray}" 
                                    SelectedValueBinding="{Binding IsActive}" SelectedValuePath="BoolStatus" DisplayMemberPath="VerbalStatus"/>-->
            <DataGridComboBoxColumn Header="ActivityStatus" SelectedItemBinding="{Binding IsActive, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
                <DataGridComboBoxColumn.ItemsSource>
                    <x:Array Type="system:Boolean">
                        <system:Boolean>True</system:Boolean>
                        <system:Boolean>False</system:Boolean>
                    </x:Array>
                </DataGridComboBoxColumn.ItemsSource>
            </DataGridComboBoxColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

  1. DataGrid viewmodel:

    DataGrid视图模型:

    public class DataGridMainDataContext
    

    { public DataGridMainDataContext() { Collection = new ObservableCollection(new List { new UserData { UName = "Greg", IsActive = false, }, new UserData { UName = "Joe", IsActive = false, }, new UserData { UName = "Iv", IsActive = false, } });

    {public DataGridMainDataContext(){Collection = new ObservableCollection(new List {new UserData {UName =“Greg”,IsActive = false,},new UserData {UName =“Joe”,IsActive = false,},new UserData {UName =“ Iv“,IsActive = false,}});

    }
    
    public ObservableCollection<UserData> Collection { get; set; }
    

    }

    }

  2. Models: public class UserData : BaseObservableObject { private string _uName; private object _countryData; private bool _isActive;

    模型:公共类UserData:BaseObservableObject {private string _uName;私有对象_countryData;私人布尔_isActive;

    public bool IsActive
    {
        get { return _isActive; }
        set
        {
            _isActive = value;
            OnPropertyChanged();
        }
    }
    
    public string UName
    {
        get { return _uName; }
        set
        {
            _uName = value;
            OnPropertyChanged();
        }
    }
    
    public object CountryData
    {
        get { return _countryData; }
        set
        {
            _countryData = value;
            OnPropertyChanged();
        }
    }
    

    }

    }

    public class ActivityStatus:BaseObservableObject { private bool _boolStatus; private string _verbalStatus;

    public class ActivityStatus:BaseObservableObject {private bool _boolStatus; private string _verbalStatus;

    public bool BoolStatus
    {
        get { return _boolStatus; }
        set
        {
            _boolStatus = value;
            OnPropertyChanged();
        }
    }
    
    public string VerbalStatus
    {
        get { return _verbalStatus; }
        set
        {
            _verbalStatus = value;
            OnPropertyChanged();
        }
    }
    

    }

    }

    public class Country : BaseObservableObject { private string _countryName; private string _countryPop;

    public class国家:BaseObservableObject {private string _countryName; private string _countryPop;

    public string CountryName
    {
        get { return _countryName; }
        set
        {
            _countryName = value;
            OnPropertyChanged();
        }
    }
    
    public string CountryPop
    {
        get { return _countryPop; }
        set
        {
            _countryPop = value;
            OnPropertyChanged();
        }
    }
    
    public Country() { }
    public Country(string n, string d)
    {
        this.CountryName = n;
        this.CountryPop = d;
    }
    

    } Hope it will help you.

    希望它会对你有所帮助。

regards,

问候,