Mister 832 Mister 832 - 2 months ago 10
C# Question

How to Customise Header of DataGrid with Databound Itemscontrol

I tried to create a customized header of a

datagrid
containing an
itemscontrol
, which is bound to an
ObservableCollection<DateTime>
.

(Basically, I want to create 12 columns, one for each month-> see picture).

enter image description here

Why does this code does not work?

Code

<DataGrid x:Name="dgProjects" AutoGenerateColumns="False" ItemsSource="{Binding Projects}" AlternationCount="2" AlternatingRowBackground="LightGray">
<DataGrid.Columns>
...
<DataGridTemplateColumn Width="*">
<DataGridTemplateColumn.HeaderTemplate>
<DataTemplate>
<ItemsControl Grid.Row="1" ItemsSource="{Binding Path=Monate}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ActualWidth}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Date}" Background="LightGreen" Margin="1"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>


Update I narrowed the problem down to the Binding. The following code works finde

<DataGridTemplateColumn.HeaderTemplate>
<DataTemplate>
<Grid>
<ItemsControl ItemsSource="{Binding Projects}">
<TextBlock Text="asdf" Background="LightGreen" Margin="1"/>
<TextBlock Text="asdf" Background="LightGreen" Margin="1"/>
<TextBlock Text="asdf" Background="LightGreen" Margin="1"/>
</ItemsControl>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>


Update Viewmodel

public class vmProjektplanung : INotifyPropertyChanged
{
...
#region "Monate"

public event System.Collections.Specialized.NotifyCollectionChangedEventHandler OnMonateChanged;

private List<DateTime> monate;

public List<DateTime> Monate
{
get { return monate; }
set { monate = value; OnPropertyChanged(new PropertyChangedEventArgs("Monate")); }
}

private void Monate_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
OnMonateChanged?.Invoke(sender, e);
}

#endregion
...
}

Answer

There is a problem since your binding for the dates doesn't see the data context.

This should fix the issue by referencing the data grid by name.

<DataTemplate>
       <ItemsControl ItemsSource="{Binding DataContext.Monate, ElementName=dgProjects}"
Comments