Search code examples
wpfbindingdatagriddatagridcomboboxcolumnprogrammatically-created

datagridcomboboxcolumn binding in code


I'd like to do this entirely in code, no XAML: Given are

DataGridComboBoxColumn myDGCBC = new DataGridComboBoxColumn();
ObservableCollection<string> DataSource = new ObservableCollection<string>{"Option1", "Option2"};
myDGCBC.ItemsSource = DataSource;

ObservableCollection<MyStructure> MyObject = new ObservableCollection<MyStructure>;

and

public class MyStructure
{
   ... several properties ... // pseudocode, obviously
   public string SelectedValue { get; set; }
}

I am interested in (binding) receiving the selected values from all the comboxboxes in the column into the SelectedValue property.

I tried several ideas from SO, but to no avail.

Help! Thanks.


Solution

  • Assuming a DataGird is already defined in xaml, you should set proper bindings for both DataGrid and DataGridComboBoxColumn.

    Here is an example to give you an idea:

    Xaml:

    <Grid >
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <DataGrid x:Name="myGrid" AutoGenerateColumns="False"/>
        <Button Grid.Row="1"  Content="test" Click="Button_Click"/>
    </Grid>
    

    MainWindow.cs:

        //DataGrid ItemsSource
        public ObservableCollection<MyStructure> DataSource { get; set; }
    
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
    
            // Initializing DataGrid.ItemsSource
            DataSource = new ObservableCollection<MyStructure>();
            DataSource.Add(new MyStructure());
    
            // Creating new DataGridComboBoxColumn 
            DataGridComboBoxColumn myDGCBC = new DataGridComboBoxColumn();
            myDGCBC.Header = "cmbColumn";
    
            // Binding DataGridComboBoxColumn.ItemsSource and DataGridComboBoxColumn.SelectedItem
            var cmbItems = new ObservableCollection<string> { "Option1", "Option2" };
            myDGCBC.ItemsSource = cmbItems;
            myDGCBC.SelectedItemBinding = new Binding("SelectedValue");
            // Adding DataGridComboBoxColumn to the DataGrid
            myGrid.Columns.Add(myDGCBC);
    
            // Binding DataGrid.ItemsSource 
            Binding binding = new Binding();
            binding.Source = DataSource;
            BindingOperations.SetBinding(myGrid, DataGrid.ItemsSourceProperty, binding);
        }
    
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //This is just to check whether SelectedValue is set properly:
            string selectedValue = DataSource[0].SelectedValue;
        }