1

如何让 aDataGridTextColumn显示'-'(连字符)而不是0

以下是当前设置数据网格的方式:

<Grid>
  <DataGrid x:Name="EmployeeHours"
            AutoGenerateColumns="False"
            ItemsSource="{Binding EmployeeHoursLastWeek}"
            Width="Auto">
    <DataGrid.Columns>
      <DataGridTextColumn Header="PerceptionistID"
                          Binding="{Binding PerceptionistID}"
                          Width="100" />
      <DataGridTextColumn Header="Week Of"
                          Binding="{Binding WeekOf, StringFormat={}{0:MM/dd/yyyy}}"
                          Width="75" />
      <DataGridTextColumn Header="Regular Hours"
                          Binding="{Binding WorkHours}"
                          Width="100" />
      <DataGridTextColumn Header="PTO Hours"
                          Binding="{Binding PTOHours}"
                          Width="100" />
      <DataGridTextColumn Header="Holiday Hours"
                          Binding="{Binding HolidayHours}"
                          Width="100" />
    </DataGrid.Columns>
  </DataGrid>
</Grid>

PTOHours 和 HolidayHours 通常为 0,如果任何值为 0 的单元格显示“-”,则更容易识别值为 0 的单元格。

4

1 回答 1

6

你可以为它使用一个值转换器

<Grid>
  <Grid.Resources>
    <local:HoursToMinusConverter x:Key="HoursToMinusConverter" />
  </Grid.Resources>

  <DataGrid x:Name="EmployeeHours"
            AutoGenerateColumns="False"
            ItemsSource="{Binding EmployeeHoursLastWeek}"
            Width="Auto">
    <DataGrid.Columns>
      <DataGridTextColumn Header="PerceptionistID"
                          Binding="{Binding PerceptionistID}"
                          Width="100" />
      <DataGridTextColumn Header="Week Of"
                          Binding="{Binding WeekOf, StringFormat={}{0:MM/dd/yyyy}}"
                          Width="75" />
      <DataGridTextColumn Header="Regular Hours"
                          Binding="{Binding WorkHours}"
                          Width="100" />
      <DataGridTextColumn Header="PTO Hours"
                          Binding="{Binding PTOHours, Converter={StaticResource HoursToMinusConverter}}"
                          Width="100" />
      <DataGridTextColumn Header="Holiday Hours"
                          Binding="{Binding HolidayHours, Converter={StaticResource HoursToMinusConverter}}"
                          Width="100" />
    </DataGrid.Columns>
  </DataGrid>
</Grid>

这是转换器

public class HoursToMinusConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
    if (value is int) {
      return (int)value > 0 ? value.ToString() : "-";
    }
    return string.Empty;
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
    if (value is string) {
      int intValue;
      if (!int.TryParse((string)value, out intValue)) {
        intValue = 0;
      }
      return intValue;
    }
    return 0;
  }
}

希望这可以帮助

于 2011-12-13T19:45:48.973 回答