question

78669366 avatar image
0 Votes"
78669366 asked PeterFleischer-3316 edited

Adding a calculated property in ObservableCollection<T> inherited class

Hi

I fill an ObservableCollection<T> from a data source. I need to add a ‘header’ calculated string property that concats several properties in the observable collection. How can I achieve this?

Thanks

Regards

dotnet-csharp
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@78669366
I don't quite understand what you mean, could you please give us an example?
What is the original data and what will the later data look like?

0 Votes 0 ·

1 Answer

PeterFleischer-3316 avatar image
0 Votes"
PeterFleischer-3316 answered PeterFleischer-3316 edited

Hi,
you can use partial classes to extend for calculated 'header'. Try following demo:

XAML:

 <Window x:Class="WpfApp1.Window072"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:local="clr-namespace:WpfApp072"
         mc:Ignorable="d"
         Title="Window072" Height="450" Width="800">
   <Window.DataContext>
     <local:ViewModel/>
   </Window.DataContext>
   <Grid>
     <DataGrid ItemsSource="{Binding View}"/>
   </Grid>
 </Window>

ViewModel and data classes:

 using System.Collections.ObjectModel;
 using System.ComponentModel;
 using System.Windows;
 using System.Windows.Data;
    
 namespace WpfApp072
 {
   public class ViewModel
   {
     public ViewModel() => cvs.Source = LodData();
    
     CollectionViewSource cvs = new CollectionViewSource();
     public ICollectionView View { get => cvs.View; }
    
     private ObservableCollection<Data> LodData()
     {
       ObservableCollection<Data> col = new ObservableCollection<Data>();
       for (int i = 1; i < 10; i++) col.Add(new Data() { Text1 = $"A {i}", Text2 = $"B {i}" });
       return col;
     }
   }
    
   public partial class Data
   {
     public string Text1 { get; set; }
     public string Text2 { get; set; }
   }
    
   public partial class Data
   {
     public string header { get => $"{Text1} - {Text2}"; }
   }
 }

Result:

130565-x.png



x.png (26.6 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.