WPF/DataGrid: Binding to different properties for displaying and editing

蓝咒 提交于 2021-01-28 00:51:51

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/54774451/wpf-datagrid-binding-to-different-properties-for-displaying-and-editing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!