How can I change a wpf Databound grid cell based on the cell value?

I'm relatively new to WPF, and am trying to change certain grid cells where the bound values are decimal zeros. The intent is to leave the cell blank where the cell has 0's. For example, if the TranDeposit column is zeros, I would like to change that to blanks. In ASP.NET this is very possible by using the DataBound event. The XAML code follows:

<DataGrid x:Name="transactionsDataGrid" Grid.Row="3" AutoGenerateColumns="False" EnableRowVirtualization="True"
                    ItemsSource="{Binding}" RowDetailsVisibilityMode="VisibleWhenSelected" RowHeaderWidth="0" Padding="10,0,0,0"
                    AlternatingRowBackground="#FF888888" GridLinesVisibility="Horizontal" SelectionUnit="FullRow" RowBackground="#FFCCCCCC" VerticalAlignment="Top" SelectedIndex="0"
                    HeadersVisibility="Column" Background="#FF292929" Height="355" SelectionChanged="TransactionsDataGrid_SelectionChanged" CanUserAddRows="false" Margin="5,0,5,0"
                           Loaded="DataGrid_RowLoaded">

                        <DataGrid.Columns>
                            <DataGridTextColumn x:Name="tranDateColumn" Binding="{Binding TranDate, StringFormat=MM/dd/yyyy}" Header="Date" Width="90" IsReadOnly="True"/>
                            <DataGridTextColumn x:Name="tranDescriptionColumn" Binding="{Binding TranDescription}" Header="Description" Width="*" IsReadOnly="True"/>
                            <DataGridTextColumn x:Name="tranCategoryColumn" Binding="{Binding TranCategory}" Header="Category" Width="340" IsReadOnly="True">
                                <DataGridTextColumn.ElementStyle>
                                    <Style TargetType="TextBlock">
                                        <!--<Setter Property="HorizontalAlignment" Value="Right" />-->
                                        <Setter Property="ToolTip" Value="{Binding Path=TranCategory}"/>
                                    </Style>
                                </DataGridTextColumn.ElementStyle>
                            </DataGridTextColumn>
                            <DataGridTextColumn x:Name="tranNotesColumn" Binding="{Binding TranNotes}" Header="Notes" Width="120" IsReadOnly="True"/>
                            <DataGridCheckBoxColumn x:Name="tranTaxColumn" Binding="{Binding TranTax}" Header="Tax" Width="SizeToHeader" IsReadOnly="True"/>
                            <DataGridCheckBoxColumn x:Name="tranClearedColumn" Binding="{Binding TranCleared}" Header="Cleared" Width="SizeToHeader" IsReadOnly="True" />
                            <DataGridTextColumn x:Name="tranDepositColumn" Binding="{Binding TranDeposit}" Header="Deposit" Width="80" IsReadOnly="True"/>
                            <DataGridTextColumn x:Name="tranWithdrawlColumn" Binding="{Binding TranWithdrawl}" Header="Withdrawal" Width="80" IsReadOnly="True" />
                            <DataGridTextColumn x:Name="tranBalanceColumn" Binding="{Binding TranBalance}" Header="Balance" Width="80" IsReadOnly="True"/>
                        </DataGrid.Columns>
                    </DataGrid>

As you can see I have tried to use the Loaded event to access the row, however, there is no row available to dynamically change for this event. I have tried the LoadingRow event, however, when attempting to use the very popular datagrid helper extension "DataGridHelper", I get a NullReferenceException in the GetCell method on the line:

presenter = GetVisualChild<DataGridCellsPresenter>(row);

the row value is correct, but the presenter value is null.

public static DataGridCell GetCell(this DataGrid grid, DataGridRow row, int column)
    {
        if (row != null)
        {
            DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
            if (presenter == null)
            {
                grid.ScrollIntoView(row, grid.Columns[column]);
                presenter = GetVisualChild<DataGridCellsPresenter>(row);
            }

            DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            return cell;
        }
        return null;
    }

Not sure where to go at this point and have searched all over the web for an answer. I'd really appreciate any help


Use a value converter, something along the lines of:

public class ZeroToBlank: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is int && (int)value == 0)
            return string.Empty;

        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (string.IsNullOrEmpty(value))
            return 0;

        return value;
    } 
}

You'll need to add a reference to the namespace in your XAML:

xmlns:converters="YourNamespace.Converters"

Then add as a resource:

<UserControl.Resources>
    <converters:ZeroToBlankConverter x:Key="ZeroToBlankConverter" />
</UserControl.Resources>

And finally in binding:

Binding="{Binding TranDeposit, Converter={StaticResource ZeroToBlankConverter}}"
链接地址: http://www.djcxy.com/p/71122.html

上一篇: 从外部绑定到ContentPresenter的视觉元素/子项

下一篇: 如何根据单元格值更改wpf Databound网格单元格?