Search code examples
entity-frameworkdata-bindingdatagridcomboboxcolumn

1:n bind to DataGridComboBoxColumn


I would like to display a 1:n relation in a DataGrid (CollectioViewSource). Based on the EntityFramework.

Works so far: Display the essential data, display the DataGridComboBoxColumn, possible to choose other entries in the DataGridComboBoxColumn.

Doesn't work: Save changes with _context.SaveChanges(); (_context is an instance of DatabaseContext). So, if I change an other Typ in the DataGridComboBoxColumn and try to safe I got: "System.InvalidOperationException: The property 'TypId' is a part of the key-information of the object and can't change'. (Own translation from German to English..)

Info: I can change the Operation.TypId Attribut directly at the database with no error.

XAML:

    <Page x:Class="ProdPlanNET.Views.OperationPage"
   <Page.Resources>

    <CollectionViewSource x:Key="operationViewSource"/>
</Page.Resources>
<Grid >
    <Grid.Resources>
        <CollectionViewSource x:Key="source" Source="{Binding Types, Mode=OneTime}"/>
    </Grid.Resources>

    <DataGrid DataContext="{StaticResource operationViewSource}" AutoGenerateColumns="False" Margin="8,112,8,8" IsReadOnly="False" ItemsSource="{Binding}">
        <DataGrid.Columns>
            <DataGridTextColumn IsReadOnly="True" Binding="{Binding OperationId}"  
                            Header="Operation Id" Width="SizeToHeader"/>
            <DataGridTextColumn Binding="{Binding Name}"  
                            Header="Operation Name" Width="SizeToHeader"/>

            <DataGridComboBoxColumn ItemsSource="{Binding Source={StaticResource source}}"
                                    SelectedValuePath="TypId" DisplayMemberPath="Name" SelectedValueBinding="{Binding Path=Typ.TypId}" />
     </DataGrid.Columns>

My ViewModel:

   namespace ProdPlanNET.ViewModels
   {
      class OperationPageViewModel : BaseViewModel
{

    public CollectionViewSource cvs = new CollectionViewSource();
    private DatabaseContext _context = new DatabaseContext();

    public ObservableCollection<Typ> Types
    {
        get
        {
            return _context.Types.Local;
        }
        set { }
    }

    System.Windows.Data.CollectionViewSource operationViewSource;

    public OperationPageViewModel(object viewSource)
    {
        this.operationViewSource = ((System.Windows.Data.CollectionViewSource)viewSource);

        _context.Types.Load();
        _context.Workplaces.Load();
        _context.Operations.Load();

        operationViewSource.Source = _context.Operations.Local;

    }
    public void SaveCommand()
    {    

            _context.SaveChanges();
   }}}

Solution

  • Got it by my self.

      <DataGridComboBoxColumn ItemsSource="{Binding Source={StaticResource source}}" 
                      SelectedValueBinding="{Binding Typ, Mode=TwoWay}" DisplayMemberPath="Name" />
    

    Hope it helps somebody.