I have multiple DataGrids to manage the data of my database. The functionallity also includes adding new rows. The problem is though, that in my given example there is a dependency between the created row, and the DataGrid's DataContext set by another DataGrid. In my case I've got:
Parties - A party can have n Tracks. If you change the selection of the Party DataGrid, you change the view of the Track DataGrid.
Tracks - A Track has essentially a reference back to the Party.
XAML:
<DataGrid AutoGenerateColumns="False" SelectionMode="Single" DataContext="{Binding CurrentParty}" ItemsSource="{Binding Tracks}" SelectedItem="{Binding CurrentTrack}">
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="_Delete" Command="{Binding DeleteTrackCommand}"/>
</ContextMenu>
</DataGrid.ContextMenu>
<DataGrid.Columns>
<DataGridTextColumn IsReadOnly="True" Header="Votes" Binding="{Binding Path=Votes}">
<DataGridTextColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="LightGray" />
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
<DataGridTemplateColumn Header="Interpret" IsReadOnly="False">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Interpret}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Interpret}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Title" IsReadOnly="False">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Title}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Title}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="URL" IsReadOnly="False">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Url}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Url}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Code in ViewModel:
public TrackVM() {
// requires the "CurrentParty" from DataContext.
}
I could access the DataContext in the code behind, but that would kinda break the MVVM architecture, wouldn't it. What I want to do / have instead is: pass the CurrentParty object to the default constructor.