tags:

views:

34

answers:

1

I have a XML with 3 values, they are 'name', 'department', 'value'. I want to display a data grid with four columns like Name, department, credit and debit. When I have a value positive in 'value' column I want to enter the value in debit column and 0 in credit column and vice versa.

+1  A: 

Hi there,

there are several ways to solve this problem. One that is probably the cleanest would be to add a DataGridTemplateColumn for credit as well as debit, bind both columns to "Value" and then toggle the Visibility property of the element that diaplys the value (e.g. TextBlock) by using also a binding to "Value" and a converter. Example:

    <DataGrid
        AutoGenerateColumns="False">
        <DataGrid.Resources>
            <converters:ValueToVisibilityConverter
                x:Key="ValueToVisibilityConverter" />
        </DataGrid.Resources>
        <DataGrid.Columns>
            <DataGridTemplateColumn
                Header="Credit">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock
                            Text="{Binding Path=Value}"
                            Visibility="{Binding Path=Value, Converter={StaticResource CreditToVisibilityConverter}}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn
                Header="Debit">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock
                            Text="{Binding Path=Value}"
                            Visibility="{Binding Path=Value, Converter={StaticResource DebitToVisibilityConverter}}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

The converter for credit could look like this:

public class CreditToVisibilityConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return (double)value >= 0 ? Visibility.Visible : Visibility.Collapsed;
    }

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

    #endregion
}

The converter for debit would be almost the same, only with the "value >= 0 portion" changed to "value < 0" of course.

Cheers, Alex

alexander.biskop