wpf 如何以编程方式将 DataGrid 列设置为 DatePicker 输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28035239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:51:50  来源:igfitidea点击:

How to set a DataGrid column to DatePicker input programmatically

c#wpfdatagriddatatabledatepicker

提问by Charles Clayton

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 DatePickersDatePickersDateTimePickers 中创建特定列,但它们都是通过 XAML 完成的。做这样的事情:

<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:

结果是这样:

enter image description here

在此处输入图片说明

Is there a way to do in in C#?

有没有办法在 C# 中做?

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

我从 SQL 数据库输入一个 DataTable 并将它绑定到一个 DataGrid。像这样:

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:

我的 XAML 看起来像这样:

<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

但那些最终只是作为单元格中的日期字符串,而不是 DatePicker 输入类型?有没有办法做到这一点?例如

        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:

如果我可以部分通过 XAML 完成它也没关系。例如,如果我制作我的 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?

DataTable 中的日期列我像这样加载,taskTable.DataContext = dataTable.DefaultView;我可以以某种方式使日期列与 C# 中的 DataTable 中的数据在来自 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?

有任何想法吗?

enter image description here

在此处输入图片说明

回答by Charles Clayton

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#

C#

Inside public partial class MainWindow: window

里面 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 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

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

这是我用于数据网格的 XMAL

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

enter image description here

在此处输入图片说明