8,757
社区成员
发帖
与我相关
我的任务
分享using System;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Markup;
namespace Common
{
public class DataGridDateTimeFormatBehavior: Behavior<DataGrid>
{
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>(AssociatedObject_AutoGeneratingColumn);
}
void AssociatedObject_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyType == typeof(DateTime))
{
DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
templateColumn.Header = e.PropertyName;
var CellTemp = new StringBuilder();
CellTemp.Append("<DataTemplate ");
CellTemp.Append("xmlns='http://schemas.microsoft.com/client/2007' ");
CellTemp.Append("xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' >");
CellTemp.Append("<Grid>");
CellTemp.Append("<TextBlock ");
CellTemp.Append("Text = '{Binding ");
CellTemp.Append(e.PropertyName);
CellTemp.Append(", Converter={StaticResource ShortDateConverter}}' ");
CellTemp.Append(" VerticalAlignment='Center' />");
CellTemp.Append("</Grid>");
CellTemp.Append("</DataTemplate>");
templateColumn.CellTemplate = (DataTemplate)XamlReader.Load(CellTemp.ToString());
templateColumn.CanUserSort = true;
templateColumn.IsReadOnly = true;
e.Column = templateColumn;
}
}
}
}