WPF: how to use DatePicker in XAML-DataGrid

In a standalone WPF application, I got a DataGrid for entering some values. For text values, this works like this:

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding MyCollection}">
  <DataGrid.Columns>
    <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
    <DataGridTextColumn Header="Description" Binding="{Binding Description}"/>
  </DataGrid.Columns>
</DataGrid>

But now I would like to introduce some dates using DatePicker instead of text entry, but not or something like that.

So, how do I get a DatePicker (or something else) as an input field in a DataGrid?

+3
source share
2 answers

Use DataGridTemplateColumn . There you can specify templates for editing and normal state. See an example in the article. He will show you how to use.

+6
source

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));
    }
}
0

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


All Articles