c# – 如何使用Databound Itemscontrol自定义DataGrid的标头

我尝试创建一个包含itemscontrol的datagrid的自定义标头,该标头绑定到ObservableCollection< DateTime>.

(基本上,我想创建12列,每月一列 – >参见图片).

《c# – 如何使用Databound Itemscontrol自定义DataGrid的标头》

为什么这段代码不起作用?

<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>

更新我将问题缩小到Binding.以下代码适用于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>

更新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
        ...
    }

最佳答案 由于您对日期的绑定没有看到数据上下文,因此存在问题.

这应该通过按名称引用数据网格来解决问题.

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