2

3 개의 DateTime과 다른 2 개의 문자열이 5 개의 열로 구성된 자동 생성 DataGrid를 만들었습니다. datetime 열 항목의 끝에서 시간을 제거 할 수 있어야합니다.자동 생성 된 Datagrid의 DateTime 변환기

일반적으로 나는 dateconverter를 사용하지만 이상한 결과를 얻고 있는데, 이는 datagrid뿐 아니라 datetime 열에도 적용되기 때문에 이것이라고 생각합니다.

누구든지 해결할 수 있습니까? 거기에 변환기를 적용 datetime 열을 밖으로 단일 방법은 무엇입니까?

감사와 나는 다음과 같은 몇 가지 코드를 첨부 할 수 있습니다 :

에서 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; 
      } 
     } 

} 

답변

5

이 문제를 해결할 수 있습니다. 이

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; 
      } 
     } 

간단한 계산기 그것은 당신의 DataGrid_AutoGeneratingColumn 이벤트에서이 코드로도 작동

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; 
    } 
} 
+0

감사합니다. o) – domsbrown

1

을 그 사건이

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

처럼 DataGridAutoGeneratingColumn 이벤트를 처리하여 blem 처리기 :

데이터 GridBoundColumn col = e.Column as DataGridTextColumn;

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

여기에서는 변환기를 사용하지 않고 날짜 열의 날짜 형식 만 변경합니다.

관련 문제