自动生成的数据网格中的日期时间转换器

发布于 2024-12-10 11:28:08 字数 5113 浏览 0 评论 0原文

我创建了一个包含 5 列的自动生成的数据网格,其中 3 列是日期时间,另外 2 列是字符串。我需要能够从日期时间列条目末尾删除时间。

通常我使用日期转换器,但我从中得到奇怪的结果,我猜这是因为它应用于整个数据网格而不仅仅是日期时间列。

谁能帮我解决这个问题吗?有没有办法挑出日期时间列来应用转换器?

谢谢,我将在下面附加一些代码:

MainPage.xaml:

    <UserControl x:Class="Peppermint.Flix.UI.Views.MainPage"
    xmlns:my="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
             xmlns:local="clr-namespace:Peppermint.Flix.UI"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

    <UserControl.Resources>
        <local:DateTimeConverter x:Key="DateTimeConverter" />
        </UserControl.Resources>

        <Grid x:Name="LayoutRoot" Background="White">

        <Grid.RowDefinitions>
            <RowDefinition Height="0.5*" />
            <RowDefinition Height="10*" />
        </Grid.RowDefinitions>

        <Grid x:Name="QuickNav" Grid.Row="0">

            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="0.2*"/>
                <ColumnDefinition Width="1*"/>
            </Grid.ColumnDefinitions>

            <Grid x:Name="ComboBox" Grid.Column="0">
        <ComboBox HorizontalAlignment="Stretch" Height="20" ItemsSource="{Binding NavItems}" SelectedItem="{Binding NavItem, Mode=TwoWay}" />
            </Grid>

            <Grid x:Name="GoButton" Grid.Column="1">
                <Button Content="Go" HorizontalAlignment="Left" Height="20" Command="{Binding GoCommand, Mode=OneTime}"  />
            </Grid>
        </Grid>

        <Grid x:Name="DataGrid" Grid.Row="1" >
            <sdk:DataGrid HorizontalAlignment="Stretch"  VerticalAlignment="Stretch" AutoGenerateColumns="True"  ItemsSource="{Binding TransferPackages, Converter={StaticResource DateTimeConverter} }"/>
</Grid>
    </Grid>
</UserControl>

MainViewModel.cs:

    public class MainViewModel : ViewModelBase
    {

        private string _navItem;
        private TransferPackageViewModel _data;

        #region Constructor
        public MainViewModel()
        {
            GoCommand = new DelegateCommand<object>(QuickNavGo);
            TransferPackages = new ObservableCollection<TransferPackageViewModel>();
            NavItems = new List<string> { "QUICK NAV", "New Transfer Package" };
            TransferPackages.Add(new TransferPackageViewModel { TransferPackageName = "Harry Potter 7 The Golden Amulet in 4D (12A)", CreatedBy = "Bilbo Baggins" });
            TransferPackages.Add(new TransferPackageViewModel { TransferPackageName = "Harry Potter 8 The Hairy InnKeeper in 4D (12A)", CreatedBy = "Bilbo Baggins" });
            TransferPackages.Add(new TransferPackageViewModel { TransferPackageName = "Harry Potter 7 The Milking the Cow in 5D (12A)", CreatedBy = "Bilbo Baggins" });

        }
        #endregion

        public TransferPackageViewModel Data
        {
            get { return _data; }
            set { _data = value; OnPropertyChanged("Data"); }
        }

        public void QuickNavGo(object obj)
        {
            MessageBox.Show("This will open the new Transfer Package Window");
        }

        public string NavItem 
        {
            get { return _navItem; }
            set { _navItem = value; OnPropertyChanged("NavItem"); } 
        }

        public ObservableCollection<TransferPackageViewModel> TransferPackages { get; set; }
        public List<string> NavItems { get; set; }
        public ICommand GoCommand { get; set; }

    }
}

DateTimeConverter.cs:

    public class DateTimeConverter : IValueConverter
        {

            public object Convert(object value, Type targetType,
                                      object parameter, CultureInfo culture)
            {
                if (parameter != null)
                {
                    string formatString = parameter.ToString();

                    if (!string.IsNullOrEmpty(formatString))
                    {
                        return string.Format(culture, formatString, value);
                    }
                }

                return value.ToString();
            }

            public object ConvertBack(object value, Type targetType,
                                      object parameter, CultureInfo culture)
            {
                if (value != null)
                {
                    return DateTime.Parse(value.ToString());
                }
                return value;
            }
        }

}

I have created an autogenerated datagrid with 5 columns, 3 of which are DateTime and the other 2 are Strings. I need to be able to remove the time from the end of the datetime columns entries.

Normally i use a dateconverter but i am getting strange results from it, i'm guessing this is because its applied on the whole datagrid and not just the datetime columns.

Can anyone help me fix this? is there a way to single out the datetime columns to apply the converter?

Thanks and i'll attach some code below:

MainPage.xaml:

    <UserControl x:Class="Peppermint.Flix.UI.Views.MainPage"
    xmlns:my="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
             xmlns:local="clr-namespace:Peppermint.Flix.UI"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

    <UserControl.Resources>
        <local:DateTimeConverter x:Key="DateTimeConverter" />
        </UserControl.Resources>

        <Grid x:Name="LayoutRoot" Background="White">

        <Grid.RowDefinitions>
            <RowDefinition Height="0.5*" />
            <RowDefinition Height="10*" />
        </Grid.RowDefinitions>

        <Grid x:Name="QuickNav" Grid.Row="0">

            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="0.2*"/>
                <ColumnDefinition Width="1*"/>
            </Grid.ColumnDefinitions>

            <Grid x:Name="ComboBox" Grid.Column="0">
        <ComboBox HorizontalAlignment="Stretch" Height="20" ItemsSource="{Binding NavItems}" SelectedItem="{Binding NavItem, Mode=TwoWay}" />
            </Grid>

            <Grid x:Name="GoButton" Grid.Column="1">
                <Button Content="Go" HorizontalAlignment="Left" Height="20" Command="{Binding GoCommand, Mode=OneTime}"  />
            </Grid>
        </Grid>

        <Grid x:Name="DataGrid" Grid.Row="1" >
            <sdk:DataGrid HorizontalAlignment="Stretch"  VerticalAlignment="Stretch" AutoGenerateColumns="True"  ItemsSource="{Binding TransferPackages, Converter={StaticResource DateTimeConverter} }"/>
</Grid>
    </Grid>
</UserControl>

MainViewModel.cs:

    public class MainViewModel : ViewModelBase
    {

        private string _navItem;
        private TransferPackageViewModel _data;

        #region Constructor
        public MainViewModel()
        {
            GoCommand = new DelegateCommand<object>(QuickNavGo);
            TransferPackages = new ObservableCollection<TransferPackageViewModel>();
            NavItems = new List<string> { "QUICK NAV", "New Transfer Package" };
            TransferPackages.Add(new TransferPackageViewModel { TransferPackageName = "Harry Potter 7 The Golden Amulet in 4D (12A)", CreatedBy = "Bilbo Baggins" });
            TransferPackages.Add(new TransferPackageViewModel { TransferPackageName = "Harry Potter 8 The Hairy InnKeeper in 4D (12A)", CreatedBy = "Bilbo Baggins" });
            TransferPackages.Add(new TransferPackageViewModel { TransferPackageName = "Harry Potter 7 The Milking the Cow in 5D (12A)", CreatedBy = "Bilbo Baggins" });

        }
        #endregion

        public TransferPackageViewModel Data
        {
            get { return _data; }
            set { _data = value; OnPropertyChanged("Data"); }
        }

        public void QuickNavGo(object obj)
        {
            MessageBox.Show("This will open the new Transfer Package Window");
        }

        public string NavItem 
        {
            get { return _navItem; }
            set { _navItem = value; OnPropertyChanged("NavItem"); } 
        }

        public ObservableCollection<TransferPackageViewModel> TransferPackages { get; set; }
        public List<string> NavItems { get; set; }
        public ICommand GoCommand { get; set; }

    }
}

DateTimeConverter.cs:

    public class DateTimeConverter : IValueConverter
        {

            public object Convert(object value, Type targetType,
                                      object parameter, CultureInfo culture)
            {
                if (parameter != null)
                {
                    string formatString = parameter.ToString();

                    if (!string.IsNullOrEmpty(formatString))
                    {
                        return string.Format(culture, formatString, value);
                    }
                }

                return value.ToString();
            }

            public object ConvertBack(object value, Type targetType,
                                      object parameter, CultureInfo culture)
            {
                if (value != null)
                {
                    return DateTime.Parse(value.ToString());
                }
                return value;
            }
        }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

流心雨 2024-12-17 11:28:08

您可以通过处理 DataGridAutoGenerateColumn 事件来解决这个问题,就像

<DataGrid AutoGeneratingColumn="DataGrid_AutoGeneratingColumn" HorizontalAlignment="Stretch"  VerticalAlignment="Stretch" AutoGenerateColumns="True"  ItemsSource="{Binding TransferPackages}"/>

在该事件中执行此操作

private void DataGrid_AutoGeneratingColumn(object sender, System.Windows.Controls.DataGridAutoGeneratingColumnEventArgs e)
        {
            //your date time property
            if (e.PropertyType == typeof(System.DateTime))
            {
                DataGridTextColumn dgtc = e.Column as DataGridTextColumn;
                DateTimeConverter con = new DateTimeConverter();
                (dgtc.Binding as Binding).Converter = con;
            }
        }

和一个简单的转换器一样

public class DateTimeConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if(value != null && value.GetType() == typeof(System.DateTime))
        {
            DateTime t = (DateTime) value;
            return t.ToShortDateString();
        }
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null)
        {
            return DateTime.Parse(value.ToString());
        }
        return value;
    }
}

You can solve this problem by handling AutoGeneratingColumn event of DataGrid like this

<DataGrid AutoGeneratingColumn="DataGrid_AutoGeneratingColumn" HorizontalAlignment="Stretch"  VerticalAlignment="Stretch" AutoGenerateColumns="True"  ItemsSource="{Binding TransferPackages}"/>

in that event do this

private void DataGrid_AutoGeneratingColumn(object sender, System.Windows.Controls.DataGridAutoGeneratingColumnEventArgs e)
        {
            //your date time property
            if (e.PropertyType == typeof(System.DateTime))
            {
                DataGridTextColumn dgtc = e.Column as DataGridTextColumn;
                DateTimeConverter con = new DateTimeConverter();
                (dgtc.Binding as Binding).Converter = con;
            }
        }

and a simple converter

public class DateTimeConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if(value != null && value.GetType() == typeof(System.DateTime))
        {
            DateTime t = (DateTime) value;
            return t.ToShortDateString();
        }
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null)
        {
            return DateTime.Parse(value.ToString());
        }
        return value;
    }
}
只有一腔孤勇 2024-12-17 11:28:08

它也适用于 DataGrid_AutoGenerateColumn 事件处理程序中的以下代码片段:

DataGridBoundColumn col = e.Column as DataGridTextColumn;

if (col != null && e.PropertyType == typeof(DateTime))
{
   col.Binding.StringFormat = "{0:d}";
}

在这里,您只需更改日期列中的日期格式,无需使用转换器。

It works also with this code snippet in your DataGrid_AutoGeneratingColumn event Handler:

DataGridBoundColumn col = e.Column as DataGridTextColumn;

if (col != null && e.PropertyType == typeof(DateTime))
{
   col.Binding.StringFormat = "{0:d}";
}

Here you just change the date format in your date column without using a converter.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文