简体   繁体   English

WPF / DataGrid:绑定到不同的属性以进行显示和编辑

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

I have an object that contains eg a string property like "10; 20; 30". 我有一个对象,其中包含例如“ 10; 20; 30”之类的字符串属性。 I have also a get property that splits the string, converts each part to a double and sums them up. 我还有一个get属性,用于分割字符串,将每个部分转换为double并求和。 Thus I have "10; 20; 30" and 60.0 (as double). 因此,我有“ 10; 20; 30”和60.0(两倍)。

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"? 有没有一种方法可以在TextColumn中显示60.0(双精度),但是在编辑模式下,编辑字符串“ 10; 20; 30”吗?

So that I can bind to one property for displaying and to bind to another property for editing? 这样我可以绑定到一个属性进行显示,并绑定到另一个属性进行编辑?

You can achieve this with your existing property itself by using different template displaying and editing. 您可以通过使用不同的模板显示和编辑,利用现有属性本身来实现此目的。

Below CellTemplate and CellEditingTemplate can used for this. 下面的CellTemplateCellEditingTemplate可以用于此目的。

<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. 您可以使用IValueConverter将更新的字符串值转换为所需计算​​的double

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. 注意:您可以在ValueConverter类中为用户值添加必要的验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM