开发者

One value display two columns in data grid

开发者 https://www.devze.com 2022-12-31 05:55 出处:网络
I have a XML with 3 values, they are \'name开发者_如何学JAVA\', \'department\', \'value\'. I want to display a data grid with four columns like Name, department, credit and debit. When I have a value

I have a XML with 3 values, they are 'name开发者_如何学JAVA', '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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消