How to customize a DataGrid header using data elements

I tried to create a custom header datagridcontaining itemscontrolone that is bound to ObservableCollection<DateTime>.

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

enter image description here

Why is this code not working?

the 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 snapping. 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
        ...
    }
+4
source share
1 answer

There was a problem because your date binding does not see the data context.

This should fix the problem by specifying a data grid by name.

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

Source: https://habr.com/ru/post/1649880/


All Articles