1
<DataGrid....
<DataGrid.Resources>
  <DataTemplate DataType="{x:Type DateTime}">
        <TextBlock Text="{Binding StringFormat={}{0:d}}"  />
  </DataTemplate>
</DataGrid.Resources>
...
 <DataGridTemplateColumn Header="Время оплаты">
    <DataGridTemplateColumn.CellTemplate>
          <DataTemplate>
                <TextBlock VerticalAlignment="Center" Text="{Binding date_payment}"  Width="Auto" Height="Auto" />
           </DataTemplate>
     </DataGridTemplateColumn.CellTemplate>
 </DataGridTemplateColumn>

但是此列具有类型DateTime...我需要在此类型(字符串)上转换此列,因为我需要在此列上重命名值行,LoadingRow所以我使用事件

DataRowView item = e.Row.Item as DataRowView;
DataRow row = item.Row;
var time = row[4];
if (Convert.ToString(time) == "01.01.0001 0:00:00")
{
   row[4] = "No payment";
}

但它错了,行没有转换为字符串,请帮忙

4

3 回答 3

3

首先,您有一个单元格模板和一个数据模板。选一个。其次,既然你有一个数据模板,就没有理由创建转换器,更不用说创建代码隐藏事件处理程序了。您可以使用触发器将所有相关代码和文本字符串(如果需要本地化怎么办?)很好地保存在一个地方:

<DataTemplate TargetType="{x:Type DateTime}">
  <TextBlock x:Name="text" Text="{Binding StringFormat={}{0:d}}"/>
  <DataTemplate.Triggers>
    <DataTrigger Binding="{Binding}" Value="{x:Static DateTime.MinValue}">
      <Setter TargetName="text" Property="Text" Value="No payment"/>
    </DataTrigger>
  </DataTemplate.Triggers>
</DataTemplate>
于 2012-07-13T10:23:14.573 回答
2

如果它是 Nullable 值,您可以使用

Binding="{Binding date_payment, TargetNullValue={}Дата отсутствует}"

如果不是,请使用 IValueConverter 来检查 MinDate。这是一个如何使用转换器的示例,以及为您提供的转换器

public class DateConverter:IValueConverter
{
    private const string NoDate = "Дата отсутствует";
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if(value is DateTime)
        {
            var date = (DateTime) value;
            if(date==DateTime.MinValue)
                return NoDate;
            return date.ToString();
        }
        return NoDate;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
于 2012-07-13T10:08:59.160 回答
1

你应该为此使用转换器:

public class MyConverter : IValueConverter {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            if (value == DateTime.MinValue) {
                return "No payment";
            }
            return value.ToString();
        }

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

不仅仅是将转换器添加到您的绑定中。

于 2012-07-13T10:01:33.083 回答