0
votes

I have a datagrid for user input and each cell is a combobox for data selection. The selected value shall be binded to the itemsource of the datagrid to save the data later into my database. The combobox values shall come from a different itemsource.

UI:

                    <DataGrid ItemsSource="{Binding Users}">
                        <DataGrid.Columns>
                             <DataGridTemplateColumn Header="Firstname">
                                <DataGridTemplateColumn.CellTemplate>
                                    <HierarchicalDataTemplate>
                                        <ComboBox ItemsSource="{Binding Firstnames}" DisplayMemberPath="Name"/>
                                    </HierarchicalDataTemplate>
                                </DataGridTemplateColumn.CellTemplate>
                            </DataGridTemplateColumn>
                        </DataGrid.Columns>
                    </DataGrid>
                    <ComboBox ItemsSource="{Binding Firstnames}" DisplayMemberPath="Name">

                    </ComboBox>
                </StackPanel>

Model and ViewModel:

// Models

public class User 
{
    public string Firstname { get; set; }
    public string Lastname {get; set; }
}

public class Firstname
{
    public string Name { get; set; }
}

public class Lastname 
{
    public string Name { get; set; }
}


//ViewModel

public class GenerateViewModel : NotifyUIBase
{

    #region properties
    public ObservableCollection<User> Users { get; set; }

    public ObservableCollection<Firstname> Firstnames { get; set; }
    public ObservableCollection<Lastname> Lastnames { get; set; }

    #endregion


    #region Constructor

    public GenerateViewModel()

    {
        Firstnames = new ObservableCollection<Firstname>()
        {
            new Firstname() {Name="Firstname1"},
            new Firstname() {Name= "Firstname2"}
        };
        Lastnames = new ObservableCollection<Lastname>()
        {
            new Lastname() {Name="Lastname1"},
            new Lastname() {Name= "Lastname2"}
        };
        Users = new ObservableCollection<User> {new User()};

    }

    #endregion

    #region Methods


    #endregion


}

The combobox inside of the datagrid keeps empty, but my binding with a additional combobox outside of the datagrid works well.

1

1 Answers

1
votes

DataContext is not recognized, you have to get it from the main Window:

 <HierarchicalDataTemplate>
         <ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, 
                                         AncestorType={x:Type Window}}, 
                                         Path=DataContext.Firstnames}" 
                   DisplayMemberPath="Name"/>
 </HierarchicalDataTemplate>