how to make particular column of datagrid a combobox when AutoGenerateColumns=“True”

后端 未结 2 1280
执笔经年
执笔经年 2021-01-13 17:10

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.xam

相关标签:
2条回答
  • 2021-01-13 17:38

    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;
        }        
    }
    
    0 讨论(0)
  • 2021-01-13 17:50

    There doesn't seem to quite be a complete answer here so I'll post what I found from this question and from experimentation. I'm sure this breaks many rules but it's simple and it works

    public partial class MainWindow : Window
        {
            // define a dictionary (key vaue pair). This is your drop down code/value
            public static Dictionary<string, string> 
                  dCopyType = new Dictionary<string, string>() { 
                     { "I", "Incr." }, 
                     { "F", "Full" } 
                  };
    
    
    // If you autogenerate columns, you can use this event 
    // To selectively override each column
    // You need to define this event on the grid in the event tab in order for it to be called
    private void Entity_AutoGeneratingColumn(object sender,
                                             DataGridAutoGeneratingColumnEventArgs e)
            {
    
                // The name of the database column
                if (e.PropertyName == "CopyType")
                {
                    // heavily based on code above
                    var cb = new DataGridComboBoxColumn();
                    cb.ItemsSource = dCopyType;  // The dictionary defined above
                    cb.SelectedValuePath = "Key";  
                    cb.DisplayMemberPath = "Value";
                    cb.Header = "Copy Type"; 
                    cb.SelectedValueBinding = new Binding("CopyType");
                    e.Column = cb;
                }
    
    
            }
      } // end public partial class MainWindow
    
    0 讨论(0)
提交回复
热议问题