问题
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