how to make particular column of datagrid a combob

2019-02-19 01:13发布

问题:

I am new to MVVM . I am using wpf with MVVM in my project . So I am testing things right now before diving into an app I need to write.

My page (EmpDetailsWindow.xaml) is like this

<Grid>
    <DataGrid Name="dgEmployee" Grid.Row="0" AutoGenerateColumns="True" ItemsSource="{Binding EmployeeDataTable}" CanUserAddRows="True" CanUserDeleteRows="True" IsReadOnly="False"  />
    <Button x:Name="btnSubmit" Content="Submit" Command="{Binding SubmitCommand}" CommandParameter="sample param" HorizontalAlignment="Left" Margin="212,215,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>

and my model (EmpDetailsWindowViewModel) is as below

public class EmpDetailsWindowViewModel : INotifyPropertyChanged
    {
        public ICommand SubmitCommand { get; set; }
        public EmpDetailsWindowViewModel()
        {
            EmployeeDataTable = DataTableCreator.EmployeeDataTable();
            GenderDataTable = DataTableCreator.GenderDataTable();
            SubmitCommand = new SubmitCommand();
        }

        DataTable _employeeDataTable;
        public DataTable EmployeeDataTable
        {
            get { return _employeeDataTable;}
            set
            {
                _employeeDataTable = value;
                RaisePropertyChanged("EmployeeDataTable");
            }
        }

        DataTable _genderDataTable;
        public DataTable GenderDataTable
        {
            get { return _genderDataTable; }
            set
            {
                _genderDataTable = value;
                RaisePropertyChanged("GenderDataTable");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;


        public void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

datagrid is successfully bound to the datatable . Now I have a column "Gender" in datagrid. This should be a combobox and the item source of the cobobox is got from GenderDataTable of the view model . How can I achieve this ?

回答1:

You can do it like this

<DataGrid AutoGeneratingColumn="DataGrid_AutoGeneratingColumn"/>

private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (e.PropertyName == "Gender")
    {
        var cb = new DataGridComboBoxColumn();
        cb.ItemsSource = (DataContext as MyVM).GenderDataTable;
        cb.SelectedValueBinding = new Binding("Gender");
        e.Column = cb;
    }        
}


回答2:

In Infragistics xamDataGrid you can set it programmatically by writing appropriate logic in the FieldLayoutInitialized event.

Refer this link for more info:

http://help.infragistics.com/Help/NetAdvantage/WPF/2012.2/CLR4.0/html/xamComboEditor_Setting_the_xamComboEditor_as_an_Editor_of_a_Field_Programmatically.html



标签: wpf mvvm