WPF DataGrid'CellFormatting等效'

时间:2011-04-13 12:16:36

标签: wpf datagrid formatting wpfdatagrid

我正在尝试从WinForms转换为WPF,并且在使用DataGridView时遇到了一些困难 - > WPF DataGrid。

我已经很好地加载了所有数据,只是坚持单元格格式化。

有一个带有数字的列,但如果数字为零,而不是显示0,我希望它显示NIL。

使用DataGridView,以下工作

    Private Sub SampleDGV_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles SampleDGV.CellFormatting

    Try
        If e.RowIndex >= 0 And e.ColumnIndex = SampleDGV.Columns(CostColumn.Name).Index Then
            If CDec(e.Value.ToString) = 0 Then
                e.Value = "NIL"
                e.FormattingApplied = True
            End If
        End If
    Catch ex As Exception

    End Try


End Sub

但是现在我对WPF等价物感到困惑

1 个答案:

答案 0 :(得分:0)

我不确定是否有一种简单的方法可以做到这一点,我会这样做,这似乎有效:

使用自定义转换器定义自定义列:

<DataGrid.Resources>
    <local:ZeroToNilConverter x:Key="ZeroToNilConverter"/>
</DataGrid.Resources>
<DataGrid.Columns>
    <DataGridTextColumn Binding="{Binding Id, Converter={StaticResource ZeroToNilConverter}}" Header="Test"/>
</DataGrid.Columns>
//Sorry, i do not speak VB...
public class ZeroToNilConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        int input = 0;
        try
        {
            input = (int)value;
        }
        catch (Exception)
        {
            return value;
        }

        if (input == 0) return "NIL";
        else return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string input = value as string;
        if (input != null)
        {
            if (input == "NIL") return 0;
            else return value;
        }
        else
        {
            return value;
        }
    }
}