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