简体   繁体   中英

How to set a DataGrid column to DatePicker input programmatically

There are a few of articles explaining how to make a specific column in your DataGrid DatePickers , DatePickers , or DateTimePickers , but they all do it through XAML. Doing something like this:

<DataGrid AutoGenerateColumns="True">
        <DataGrid.Columns>

                <DataGridTextColumn Binding="{Binding Name}" />

                <DataGridTemplateColumn>
                        <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                        <DatePicker SelectedDate="{Binding Date}" />
                                </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>

        </DataGrid.Columns>
</DataGrid>

Resulting in this:

在此处输入图片说明

Is there a way to do in in C#?

I input a DataTable from a SQL database and bind it to a DataGrid. Like so:

dataGrid.DataContext = dataTable.AsDataView(); 
// or maybe dataGrid.ItemsSource = dataTable.DefaultView; 
// I'm not sure what the difference is

To my XAML that looks like this:

<DataGrid RowEditEnding="updateDatabase" ItemsSource="{Binding}" AutoGenerateColumns="True">

    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="Visibility" Value="{Binding Visibility}" />
        </Style>
    </DataGrid.RowStyle>

</DataGrid>

I can go like this:

        dataTable.Rows[0][15] = new DateTime(1991, 9, 2);

or

        DatePicker dp = new DatePicker();
        dp.SelectedDate = DateTime.Today;
        dataTable.Rows[0][14] = dp;

But those just end up as date strings in the cell, not a DatePicker input type? Is there some way to do this? For instance

        dataTable.Columns[13].DataType.Equals(typeof(DatePicker));
        dataTable.Columns[13].DataType.Equals(typeof(DatePickerTextBox));

Thanks in advance.

EDIT:

It'd also be okay if I could do it partially through XAML. For instance, if I make my XMAL:

<DataGrid RowEditEnding="updateDatabase" Name="taskTable" ItemsSource="{Binding}" AutoGenerateColumns="True" HorizontalAlignment="Left" Margin="25,50,25,25" VerticalAlignment="Top" Grid.IsSharedSizeScope="True" SelectionChanged="DataGrid_SelectionChanged_1">

    <!-- VirtualizingStackPanel.IsVirtualizing="False" -->
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="Visibility" Value="{Binding Visibility}" />
        </Style>

    </DataGrid.RowStyle>

    <DataGrid.Columns>

        <DataGridTemplateColumn Header="dates">
            <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <DatePicker SelectedDate="{Binding dates}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellEditingTemplate>
        </DataGridTemplateColumn>

    </DataGrid.Columns>                    

</DataGrid>

The dates column from the the DataTable I load like so taskTable.DataContext = dataTable.DefaultView; Could I somehow get the dates columns to be the same one, with the data from the DataTable in C# under dates with the Template from XAML?

In this example, because the headers are the same, if I Select a Date in the left column, once I press enter it will go into the dates column on the right and be saved which is good. I just want them to be the same column though.

Any ideas?

在此处输入图片说明

There are plenty of solutions for if you don't have to autogenerate the columns, but I had to allow for columns to be dynamically added and removed, so there was no way around it.

Here's what worked:

C#

Inside public partial class MainWindow: window

    public string [] dates = {"COLUMN NAMES", "THAT NEED", "TO BE DATES"};


    public void addColumnTemplates(object sender, DataGridAutoGeneratingColumnEventArgs e){

        string header = e.Column.Header.ToString();

        if ( dates.Contains(header) )
        {
            MyDataGridTemplateColumn col = new MyDataGridTemplateColumn();
            col.ColumnName = e.PropertyName; 
            col.CellTemplate = (DataTemplate)FindResource("datePickerTemplate");
            e.Column = col;
            e.Column.Header = e.PropertyName;
        }

    }

Outside public partial class MainWindow: window

public class MyDataGridTemplateColumn : DataGridTemplateColumn
{
    public string ColumnName
    {
        get;
        set;
    }

    protected override System.Windows.FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
    {
        ContentPresenter cp = (ContentPresenter)base.GenerateElement(cell, dataItem);
        BindingOperations.SetBinding(cp, ContentPresenter.ContentProperty, new Binding(this.ColumnName));
        return cp;
    }
}

public class MyData
{
    public MyData(string name, bool data) { nameData = name; showData = data; }
    public string nameData { get; set; }
    public bool showData { get; set; }
}

XMAL

For datatemplate:

<Window.Resources>
    <ResourceDictionary>

        <DataTemplate x:Key="datePickerTemplate">
            <DatePicker Text="{Binding}"
                ></DatePicker>
        </DataTemplate>

    </ResourceDictionary>
</Window.Resources>

And this is my XMAL for the datagrid

            <DataGrid ItemsSource="{Binding}" AutoGenerateColumns="True" 
                      AutoGeneratingColumn="addColumnTemplates">
            </DataGrid>

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM