ItemSource Binding on ComboBox inside a DataGrid

不问归期 提交于 2021-02-08 11:51:57

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/46118934/itemsource-binding-on-combobox-inside-a-datagrid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!