Maverick
Maverick

Reputation: 801

ItemSource Binding on ComboBox inside a DataGrid

The ComboBox inside the DataGrid is not getting populated with the List. I think there is an issue with ItemSource Path :

View (xaml code for the DataGrid) :

<DataGrid CanUserAddRows="True" ItemsSource="{Binding Path=GridCollection, Mode=TwoWay}" AutoGenerateColumns="False" IsReadOnly="False">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Column 1">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ComboBox ItemsSource="{Binding Path=DataContext.ComboBoxList}" BorderThickness="0" BorderBrush="Transparent" SelectedValue="{Binding Col1, Mode=TwoWay}"/>
                    </ComboBox>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn Header="Column 2" Width="170" Binding="{Binding Col2, Mode=TwoWay}"/>
</DataGrid>

View Model (I've created an observable collection for ItemModel, this is working fine when I update the values for Text Column and values are assigned to the Model object) :

public ObservableCollection<ItemModel> GridCollection
{
    get
    {
        return this.gridCollection;
    }
    set
    {
        this.gridCollection = value;
        base.RaisedPropertyChanged("GridCollection");
    }
}

public List<string> ComboBoxList
{
    get
    {
        return this.comboBoxList;
    }
    set
    {
        this.comboBoxList = value;
        base.RaisedPropertyChanged("GridList");
    }
}

public MultiValueViewModel(string data)
{
    this.GridCollection = new ObservableCollection<ItemModel>(); 
    this.GridCollection.Add(new ItemModel("ABC", 0));
    this.ComboBoxList = new List<string>();
    //Add items to list
}

Model (The model contains one class with 2 properties) :

public class ItemModel
{
    public ItemModel(string col1, double col2)
    {
        this.Col1 = col1;
        this.Col2 = col2;
    }

    public string Col1 { get; set; }

    public double Col2 { get; set; }
}

I've tried with Path=ComboBoxList and DataContext.ComboBoxList - bit both don't work.

Upvotes: 0

Views: 968

Answers (1)

mm8
mm8

Reputation: 169150

Try this:

<ComboBox ItemsSource="{Binding Path=DataContext.ComboBoxList, RelativeSource={RelativeSource AncestorType=DataGrid}}" BorderThickness="0" BorderBrush="Transparent" SelectedValue="{Binding Col1, Mode=TwoWay}"/>

The DataContext of the ComboBox is the ItemModel by default so you should bind to a property of the DataContext of the parent DataGrid. You could do this using a {RelativeSource} as per above.

Upvotes: 1

Related Questions