2

I have an object that contains eg a string property like "10; 20; 30". I have also a get property that splits the string, converts each part to a double and sums them up. Thus I have "10; 20; 30" and 60.0 (as double).

Now the question is. Is there a way to display the 60.0 (as double) in a TextColumn, but when going to edit mode editing the string "10; 20; 30"?

So that I can bind to one property for displaying and to bind to another property for editing?

be_mi
  • 529
  • 6
  • 21

1 Answers1

4

You can achieve this with your existing property itself by using different template displaying and editing.

Below CellTemplate and CellEditingTemplate can used for this.

<Grid>
    <Grid.Resources>
        <local:ValueConverter x:Key="ValueConverter"/>
        <DataTemplate x:Key="DisplayTemplate" >
            <TextBlock Text="{Binding StringProperty, 
                                      Converter={StaticResource ValueConverter}}"/>
        </DataTemplate>
        <DataTemplate x:Key="EditTemplate">
            <TextBox Text="{Binding StringProperty}"  />
        </DataTemplate>
    </Grid.Resources>
    <DataGrid Name="DG1" ItemsSource="{Binding Items}" AutoGenerateColumns="False" 
              CanUserAddRows="False">
        <DataGrid.Columns>
            <DataGridTemplateColumn Header="Total" 
                                    CellTemplate="{StaticResource DisplayTemplate}" 
                                    CellEditingTemplate="{StaticResource EditTemplate}" />
        </DataGrid.Columns>
    </DataGrid>
</Grid>

You can use IValueConverter to convert the updated string values to double as per your desired calculation.

public class ValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        try
        {
            double total = 0.0d;
            foreach (var item in value.ToString().Split(';'))
                total += System.Convert.ToDouble(item.Trim());
            return total;
        }
        catch
        {
            return 0.0d;
        }
    }

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

Note: You can add the necessary validation for the user values inside your ValueConverter class.

dhilmathy
  • 2,800
  • 2
  • 21
  • 29
  • Is it possible to modify a default TextColumn to have different bindings or is a DataGridTemplateColumn the only way. I'm asking, because I create the columns in code behind and I am looking for the simplest and shortest way. – be_mi Feb 20 '19 at 08:56
  • @be_mi Unfortunately [`DataGridTextColumn`](https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.datagridtextcolumn) doesn't support any sort of template for cells. Neither `CellTemplate` nor `CellEditingTemplate`. You can still create `DataGridTemplateColumn` from your code. – dhilmathy Feb 20 '19 at 09:04