如何在WPF中将DatePicker添加到DataGridTextColumn

时间:2013-09-08 03:24:59

标签: c# wpf datepicker wpf-controls wpfdatagrid

<DataGrid Name="myfirstdg"
          Grid.Row="2"
          AutoGenerateColumns="False"
          CanUserSortColumns="False"
          CanUserAddRows="False"
          CanUserDeleteRows="False"
          SelectionUnit="Cell">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Date"
                            Binding="{Binding Path=date}"
                            Width="SizeToCells"
                            IsReadOnly="True"
                            MinWidth="100"/>
    </DataGrid.Columns>
</DataGrid>

我有一个简单的DataGrid,其中包含DataGridTextColumn。如何向Datepicker添加DataGridTextColumn

3 个答案:

答案 0 :(得分:24)

正如Nitesh所说,使用DataGridTemplateColumn

<DataGridTemplateColumn Header="Pick a Date">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding myDate}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <DatePicker SelectedDate="{Binding myDate}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

答案 1 :(得分:5)

我在我的datagrids的每一列中都放了一个DatePicker,这是我在Windows构造函数中分配给DataGrid的辅助方法。此方法还取消了在DataGrid中无法显示的复杂对象的生成。

根据您的意愿进行调整!

public MainWindow()
{
    InitializeComponent();
    myDataGrid.AutoGeneratingColumn += DataGridUtilities.dataGrid_AutoGeneratingColumn;
}

public static class DataGridUtilities
{
    public static void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        if (!IsTypeOrNullableOfType(e.PropertyType, typeof(string))
            && !IsNullableOfValueType(e.PropertyType))
        {
            e.Cancel = true;
        }
        else if (IsTypeOrNullableOfType(e.PropertyType, typeof (DateTime)))
        {
            DataGridTemplateColumn col = new DataGridTemplateColumn();
            col.Header = e.Column.Header;
            FrameworkElementFactory datePickerFactoryElem = new FrameworkElementFactory(typeof (DatePicker));
            Binding dateBind= new Binding(e.PropertyName);
            dateBind.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            dateBind.Mode = BindingMode.TwoWay;
            datePickerFactoryElem.SetValue(DatePicker.SelectedDateProperty, dateBind);
            datePickerFactoryElem.SetValue(DatePicker.DisplayDateProperty, dateBind);
            DataTemplate cellTemplate = new DataTemplate();
            cellTemplate.VisualTree = datePickerFactoryElem;
            col.CellTemplate = cellTemplate;
            e.Column = col;//Set the new generated column
        }
    }


    private static bool IsTypeOrNullableOfType(Type propertyType, Type desiredType)
    {
        return (propertyType == desiredType || Nullable.GetUnderlyingType(propertyType) == desiredType);
    }

    private static bool IsNullableOfValueType(Type propertyType)
    {
        return (propertyType.IsValueType ||
                (Nullable.GetUnderlyingType(propertyType) != null &&
                 Nullable.GetUnderlyingType(propertyType).IsValueType));
    }
}

答案 2 :(得分:1)

这是基于@Guish的答案,但将其封装到一个新的列类中。

private void Grid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (e.PropertyType == typeof(DateTime))
    {
        e.Column = new DataGridDateTimeColumn((DataGridBoundColumn)e.Column);
    }
}

internal class DataGridDateTimeColumn : DataGridBoundColumn
{
    public DataGridDateTimeColumn(DataGridBoundColumn column)
    {
        Header = column.Header;
        Binding = (Binding)column.Binding;
    }

    protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
    {
        var control = new TextBlock();
        BindingOperations.SetBinding(control, TextBlock.TextProperty, Binding);
        return control;
    }

    protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
    {
        var control = new DatePicker();
        control.PreviewKeyDown += Control_PreviewKeyDown;
        BindingOperations.SetBinding(control, DatePicker.SelectedDateProperty, Binding);
        BindingOperations.SetBinding(control, DatePicker.DisplayDateProperty, Binding);
        return control;
    }

    private void Control_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if (e.Key == System.Windows.Input.Key.Return)
        {
            DataGridOwner.CommitEdit();
        }
    }
}