简体   繁体   English

在动态创建的WPF数据网格中将自定义模板分配给DateCell

[英]Assign custom template to DateCells in dynamically created WPF datagrid

I have been working on this problem for a while and I couldn't figure it out :( I have a datagrid that dynamically filled with data. Sometimes the data is in the form of date/time. 我一直在研究这个问题,我无法弄明白:(我有一个动态填充数据的数据网格。有时数据是以日期/时间的形式。

Now, I need to do two things: 现在,我需要做两件事:

1- Delete the time and show only date (eg6/1/2019 12:00:00 AM ---> 6/1/2019) 1-删除时间并仅显示日期(例如,6/1/2019上午12:00:00 ---> 6/1/2019)

2- Display datepicker on the cell upon clicking on it. 2-单击单元格上的显示日期选择器。

I googled for solutions and most of solutions are for static datagrid. 我搜索了解决方案,大多数解决方案都是针对静态数据网格。

I tried resource method but I was not successful. 我尝试了资源方法,但我没有成功。

I appreciate all of your helps 我感谢你的所有帮助

Example of date column in my datagrid: 我的数据网格中的日期列示例:

我的数据网格中的日期列示例

Something like this, perhaps? 也许是这样的事情?

namespace WpfApplication {

    public class Thing
    {
        public string Name { get; set; }
        public DateTime Date { get; set; }
    }

    public partial class MainWindow : Window
    {
        public MainWindow() {
            InitializeComponent();
            DataContext = new Thing[] {new Thing {Name = "A", Date = DateTime.Today}};
        }

        private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) {
            if (e.PropertyName == "Date")
            {
                var templateColumn = new DataGridTemplateColumn();
                templateColumn.Header = "Date";
                templateColumn.CellTemplate = (DataTemplate) Resources["DateTemplate"];
                templateColumn.CellEditingTemplate = (DataTemplate) Resources["DateEditTemplate"];
                e.Column = templateColumn;
            }
        }
    }
}


<Window x:Class="WpfApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <DataTemplate x:Key="DateTemplate">
            <TextBlock Text="{Binding Date, StringFormat='d'}" />
        </DataTemplate>
        <DataTemplate x:Key="DateEditTemplate">
            <DatePicker SelectedDate="{Binding Date, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <DataGrid AutoGenerateColumns="True" ItemsSource="{Binding}" AutoGeneratingColumn="DataGrid_AutoGeneratingColumn" />
    </Grid>
</Window>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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