HeaderTemplate in DataGrid WPF

孤者浪人 提交于 2019-12-08 05:24:43

问题


I need to have a kind of a datepicker in my datagrid header for one of the columns. When the user selects the date from this header datepicker, the system should bind this date to all the column cells with the date.
Is there a way to do it?


回答1:


the best way is to set the header's dataTemplate to a custom template containing a DatePicker whose Date is bound to one of the DataGrid's DataContext's properties, then bind the cells in this specific column to the same property.

something like this:

    <DataGrid>
        <DataGridTextColumn Binding="{Binding DataContext.myDate, RelativeSource={RelativeSource AncestorType=DataGrid}, Mode=OneWay}" >
            <DataGridTextColumn.HeaderStyle>
                <Style TargetType="{x:Type DataGridColumnHeader}">
                    <Style.Setters>
                        <Setter Property="ContentTemplate">
                            <Setter.Value>
                                <DataTemplate>
                                    <DatePicker SelectedDate={Binding myDate, Mode=TwoWay} />
                                </DataTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style.Setters>
                </Style>
            </DataGridTextColumn.HeaderStyle>
        </DataGridTextColumn>
    </DataGrid>

Disclaimer: I did not try this and am not sure about the {Binding DataContext.myDate, RelativeSource={RelativeSource AncestorType=DataGrid} thing. You would probably have do to some adjustments, but overall, this should give you a start on how to proceed




回答2:


You can modify the column's header for the DataGrid to include a DateTimePicker, then add a change event to the DateTimePicker which updates all the data in that column when the data changes.

<DataGridTextColumn Binding="{Binding Path=MyDate}">
    <DataGridTextColumn.Header>
        <!-- Add Header Here w/ DateTimePicker -->
    </DataGridTextColumn.Header>
</DataGridTextColumn>


来源:https://stackoverflow.com/questions/5248765/headertemplate-in-datagrid-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!