0
votes

I’m currently struggling with DataGrid in WPF MVVM

What I have is DataGrid, that is binded to one collection. It is displayed in DataGridTextColumn as expected and populates DataGrid. Let’s imagine I have 10 items in it. But what I need also is to have one DataGridComboBoxColumn in each row, that would be binded to the separate collection. It should contain its own values, that have no attitude to the first collection. Using that DataGrid user will determine the binding between 2 collections that are not connected logically.

The XAML code is:

<DataGrid Grid.Column="0" AutoGenerateColumns="False" CanUserAddRows="False" 
            ItemsSource="{Binding Path=ItemNamesSetting}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Initial Name item" Binding="{Binding Path=OriginalItemName}" />
        <DataGridTextColumn Header="Final Name item" Binding="{Binding Path=FinalItemName}" />
        <DataGridComboBoxColumn Header="Belongs to" Width="*" 
                                ItemsSource="{Binding Path=AttributesBindingList}"
                                DisplayMemberPath="PropName"/>
    </DataGrid.Columns>
</DataGrid>

Though it displays empty rows in ComboBox. I have seen multiple examples, that are working with DataGridComboBoxColumn bindings to the data, connected between collections by some external key. But I have 2 different collections, that are not connected.

Can you take a look where I’m wrong with this binding?

1
where is the AttributesBindingList defined?Ilan
It is set in VM like: public ObservableCollection<PropertyBindingViewModel> attributesBindingList; public ObservableCollection<PropertyBindingViewModel> AttributesBindingList { get { return attributesBindingList; } set { attributesBindingList = value; OnPropertyChangedHandler("AttributesBindingList"); } }Oleksii

1 Answers

1
votes

DataContext of your DataGridComboBoxColumn is ItemNamesSetting instance (you use OriginalItemName and FinalItemName for DataGridTextColumns), so to use AttributesBindingList in DataGridComboBoxColumn you need to change it DataContext, for example with ElementName property:

<Grid DataContext="{Binding MainVM}" Name="MainGrid">
    <DataGrid ItemsSource="{Binding SomeCollection}">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Name}"/>
            <DataGridComboBoxColumn ItemsSource="{Binding DataContext.ComboBoxCollection, ElementName=MainGrid}" />
        </DataGrid.Columns>
    </DataGrid>
</Grid>

In example i have created VM (MainVM) as DataContext for Grid. We have two properties - SomeCollection and ComboBoxCollection, but DataGridComboBoxColumn use DataContext from MainGrid.