Search code examples
c#wpfdatagridcomboboxcolumn

DataGridComboBoxColumn binding to a list of custom class


<DataGridComboBoxColumn x:Name="categoryColumn" Header="Category"     
                                    SelectedValueBinding="{Binding CategoryID}"
                                    SelectedValuePath="CategoryID"
                                    DisplayMemberPath="CategoryName"
                                    Width="200">

categoryColumn.ItemsSource = FetchData.CategoriesList;
 List<FileModel> _files = new List<FileModel>();
        _files.Clear();
        _files.Add(new FileModel
        {
            Filename = "Test.pdf",
            Title = "Test",
            Category = new CategoryModel
            {
                CategoryID = 63,
                CategoryName = "Personal"
            }
        });
        DataGrid.ItemsSource = _files;

Being new to WPF I am unable to bind the data/item source to DataGridComboboxCOlumn. Here combo box is not at all visible. Please help.


Solution

  • The problem is that the dataContext of the DataGrid isn't being passed on to the DataGridComboBoxBolumn.. because they aren't part of the same visual tree.

    So... when you try to bind to the value of the CategoryModel within the DataGrid... it cannot find it.

    Here is one approach to this problem, which uses ElementStyles to forward the dataContext by making the Column part of the same visual tree as the DataGrid:

    <!—now itemssource will find the correct DataContext-->
    <dg:DataGridComboBoxColumn Header="Current Product"
        SelectedValueBinding="{Binding Path=CurrentProduct}"
          SelectedValuePath="ProductID"
        DisplayMemberPath="ProductName">              
      <dg:DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="ComboBox">
          <Setter Property="ItemsSource" Value="{Binding Path=ProductsInCategory}" />
        </Style>
      </dg:DataGridComboBoxColumn.ElementStyle>
      <dg:DataGridComboBoxColumn.EditingElementStyle>
        <Style TargetType="ComboBox">
          <Setter Property="ItemsSource" Value="{Binding Path=ProductsInCategory}" />
        </Style>
      </dg:DataGridComboBoxColumn.EditingElementStyle>
    </dg:DataGridComboBoxColumn>
    

    You can use this approach, just make your CategoriesList a property that you can bind to:

    public ObservableCollection<CategoryModel> CategoriesList { get; set; }
    

    Then in your setup code:

    CategoriesList = FetchData.CategoriesList;
    

    (So in the above example, you would be binding the ItemsSource of your ComboBox to "CategoriesList", instead of "ProductsInCategory")