Отображать пустое поле в ListView, когда Datetime в Datatable равно 01/01/1900

#c# #wpf

#c# #wpf

Вопрос:

у меня есть DataTable dtLeaves с 5 столбцами, 2 из которых являются DateTime StartDate, EndDate столбцами, которые могут иметь значение minDate 01/01/1900 , а DataTable отображается через ListView LeavesListView , есть ли возможность для ListView отображать даты 01/01/1900 в виде пустого поля вместо фактического значения? DataTable заполняется с сервера SQL.

XAML

 <ListView x:Name="LeavesListView" Margin="10,10,13,10" Background="White" Opacity="0.8" Grid.Row="2" FontFamily="Times New Roman" FontSize="14" FlowDirection="RightToLeft" SelectionChanged="LeavesListView_SelectionChanged" MouseDoubleClick="LeavesListView_MouseDoubleClick">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="تاريخ البدء" Width="120" TextBlock.TextAlignment="Center" DisplayMemberBinding="{Binding StartDate, StringFormat=yyyy/MM/dd}" FrameworkElement.FlowDirection="RightToLeft"/>
            <GridViewColumn Header="تاريخ الأنتهاء" Width="120" TextBlock.TextAlignment="Center" DisplayMemberBinding="{Binding EndDate, StringFormat=yyyy/MM/dd}" FrameworkElement.FlowDirection="RightToLeft" />
            <GridViewColumn Header="نوع الاجازة" Width="100" FrameworkElement.FlowDirection="RightToLeft">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding LeaveType}"  Foreground="Red" />
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>
  

код для загрузки данных в ListView

 public MainWindow()
{
    InitializeComponent();
    Variables.DtLeaves = DataLoad.LoadData("EmpLeaves", "");
}
private void LoadLeaveData()
{
    try
    {
        if (EmployeesListView.SelectedIndex < 0) return;
        Variables.DtLeaves.DefaultView.RowFilter = string.Format("EmpID = '{0}'",
        Variables.Dt.Rows[EmployeesListView.SelectedIndex][0]);
        Variables.DtLeaves.DefaultView.Sort = " StartDate ASC";
        LeavesListView.ItemsSource = Variables.DtLeaves.DefaultView;
        LeaveData.DataContext = LeavesListView.SelectedItem;
        LeavesListView.SelectedIndex = 0;
        LeavesListView.Items.Refresh();
    }
    catch (Exception ex)
    {
        MessageBox.Show(string.Format("Error({0}): {1} ", ex.Message, ex.HResult), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
    }
}
  

и код в DataLoad.Cs

 public static DataTable LoadData(string tableName, string filterString)
{
    using (var con = new SqlConnection(Variables.ConString))
    {
        var table = new DataTable("");
        con.StatisticsEnabled = true;
        if (filterString != "")
            filterString = string.Format(" WHERE {0}", filterString);
        Variables.CmdString = string.Format("SELECT * FROM {0} {1}", tableName, filterString);
        var cmd = new SqlCommand(Variables.CmdString, con);
        var sda = new SqlDataAdapter(cmd);
        sda.Fill(table);
        Variables.CurrentStatistics = con.RetrieveStatistics();
        return table;
    }
}
  

Комментарии:

1. Не могли бы вы, пожалуйста, опубликовать свой код?

Ответ №1:

Вы могли бы использовать конвертер:

 public class DateConverter : IValueConverter
{
    private static readonly DateTime s_defaultDate = new DateTime(1900, 01, 01);
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        DateTime date = (DateTime)value;
        return date == s_defaultDate ? string.Empty : date.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
  

XAML:

 <ListView x:Name="LeavesListView" Margin="10,10,13,10" Background="White" Opacity="0.8" Grid.Row="2" FontFamily="Times New Roman" FontSize="14" FlowDirection="RightToLeft" SelectionChanged="LeavesListView_SelectionChanged" MouseDoubleClick="LeavesListView_MouseDoubleClick">
    <ListView.Resources>
        <local:DateConverter x:Key="DateConverter" />
    </ListView.Resources>
    <ListView.View>
        <GridView>
            <GridViewColumn Header="تاريخ البدء" Width="120" TextBlock.TextAlignment="Center" DisplayMemberBinding="{Binding StartDate, Converter={StaticResource DateConverter}}" FrameworkElement.FlowDirection="RightToLeft"/>
            <GridViewColumn Header="تاريخ الأنتهاء" Width="120" TextBlock.TextAlignment="Center" DisplayMemberBinding="{Binding EndDate, Converter={StaticResource DateConverter}}" FrameworkElement.FlowDirection="RightToLeft" />
            <GridViewColumn Header="نوع الاجازة" Width="100" FrameworkElement.FlowDirection="RightToLeft">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding LeaveType}"  Foreground="Red" />
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>
  

Комментарии:

1. Работает отлично. ty.

2. Всего одна правка в строке, <GridViewColumn Header="تاريخ البدء" Width="120" TextBlock.TextAlignment="Center" DisplayMemberBinding="{Binding EndDate, Converter={StaticResource DateConverter}}" FrameworkElement.FlowDirection="RightToLeft"/> которая должна быть <GridViewColumn Header="تاريخ البدء" Width="120" TextBlock.TextAlignment="Center" DisplayMemberBinding="{Binding StartDate, Converter={StaticResource DateConverter}}" FrameworkElement.FlowDirection="RightToLeft"/> , которую я пропустил, написала это в моем вопросе

3. @Eng. RedWolf: исправлено.