We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Migrate code behing to ViewModel

Ref: Project Branch repos

I have the following error " System.InvalidCastException....Message=Unable to cast object of type"

When I tried migrate the following source code which works to a view model. Can you help or guide me how to fix the code in MPCMassPropItemsViewModel.cs


Ref: MPCMassPropItemsView.xaml.cs

private void Demo1_Clicked(object sender, EventArgs e)

{

var filename = "BOM MasspropCalc " + Demo1.Text;

OpenDemoFile(filename); Working

viewModel.GetMasspropertyRecords(filename); Not working

}

public async void OpenDemoFile(string fileName)

{

char s = Path.DirectorySeparatorChar;

await LoadRecords($"{Constants.ScenariosDataforTestingDirectory}{s}{fileName}");

PickFileExpnd.IsExpanded = false;

}

async Task LoadRecords(string filePath)

{

using var stream = await FileSystem.OpenAppPackageFileAsync(filePath);

using StreamReader reader = new StreamReader(stream);

using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);

MPCItemsDaGr.ItemsSource = csv.GetRecords().ToList();

return;

}

Ref : MPCMassPropItemsViewModel.cs

async public void GetMasspropertyRecords(string fileName)

{

char s = Path.DirectorySeparatorChar;

using var stream = await FileSystem.OpenAppPackageFileAsync($"{Constants.ScenariosDataforTestingDirectory}{s}{fileName}");

using StreamReader reader = new StreamReader(stream);

using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);

massPropItemsCollection = (ObservableCollection)csv.GetRecords(); //Error 

}


8 Replies 1 reply marked as answer

AK Ashok Kuvaraja Syncfusion Team January 16, 2023 06:07 AM UTC

Hi Jean-Marc,


We forked your branch to validate the reported issue from our end. Unfortunately, the folder MPC-MassPropertiesCalculator-MAUIapp doesn't exist in the forked repository. So, we are unable to run and reproduce the reported issue. Please provide an issue reproducible sample. It will help us to find and sort out the problem.


Regards,

Ashok



JE Jean-Marc January 16, 2023 01:31 PM UTC

The folder  MPC-MassPropertiesCalculator-MAUIapp is in the MAUI branch.




KK Karthikraja Kalaimani Syncfusion Team January 17, 2023 11:01 AM UTC

Hi Jean, 


We checked your code csv.GetRecords() method in the MPCMassPropItemsViewModel class. The method returns the type 'MPCDataManagerLibrary.Models.MassPropItem' but is being cast to 'System.Collections.ObjectModel.ObservableCollection'1, resulting in an exception. To resolve this, we recommend using the ToObservableCollection() method to ensure the proper casting to an ObservableCollection type.

Code snippets : 
    massPropItemsCollection = csv.GetRecords<MassPropItem>().ToObservableCollection();

Regards,
Karthik Raja


JE Jean-Marc January 17, 2023 02:12 PM UTC

Hi, Karthik

The sugesstion clear the the error but the data in  massPropItemsCollection is not loaded into the datadrid control.


Regards,

Jean-Marc Flamand



KK Karthikraja Kalaimani Syncfusion Team January 18, 2023 10:28 AM UTC

Hi Jean, 

The "massPropItemsCollection" is loaded in the DataGrid when the "Scenario 01 - TWeightNot=0 and All CofG are defined (Basic Calcs).csv" button is clicked in the sample. A screenshot is provided for reference.




Regards,

Karthik Raja



JE Jean-Marc January 18, 2023 11:51 AM UTC

Hi Karthik,

Ref; MPCMassPropItemsView.xaml.cs


The source file in the repos run  the code behind method called "OpenDemoFile(filename);"

To activate the method you need to comment this line and un comment  " viewModel.GetMasspropertyRecords(filename);"

(current)

    private void Demo1_Clicked(object sender, EventArgs e)
    {
        var filename = "BOM MasspropCalc " + Demo1.Text;
        //Todo -Move Implicit code in to MPCMassPropItemsViewModel
        // Replace OpenDemoFile(filename) by viewModel.GetMasspropertyRecords(filename);
        OpenDemoFile(filename);
        // viewModel.GetMasspropertyRecords(filename);
    }

(Should be)

    private void Demo1_Clicked(object sender, EventArgs e)
    {
        var filename = "BOM MasspropCalc " + Demo1.Text;
        //Todo -Move Implicit code in to MPCMassPropItemsViewModel
        // Replace OpenDemoFile(filename) by viewModel.GetMasspropertyRecords(filename);
        //OpenDemoFile(filename);
        viewModel.GetMasspropertyRecords(filename);
    }
Sorry


NY Nirmalkumar Yuvaraj Syncfusion Team January 19, 2023 11:05 AM UTC

Hi Jean,

To reload the ItemsSource of the DataGrid i.e., massPropItemsCollection at the run time, the ViewModel class has to be inherited from INotifyPropertyChanged interface. This allows the DataGrid to be automatically updated when the data in the massPropItemsCollection changes. In this case, the ItemsSource of the DataGrid is bound to the massPropItemsCollection property, which means that when the collection is updated, the DataGrid will be updated with the new data as well.


Code Snippet:


public class MPCMassPropItemsViewModel : INotifyPropertyChanged

{

    private ObservableCollection<MassPropItem> massPropItems;

 

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(String propertyName)

    {

        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

    }

 

    public ObservableCollection<MassPropItem> massPropItemsCollection

    {

        get { return massPropItems; ; }

        set

        {

            massPropItems = value;

            NotifyPropertyChanged(nameof(massPropItemsCollection));

        }

    }

}


Please let us know if we misunderstood your query.


Regards,

Nirmalkumar


Marked as answer

JE Jean-Marc replied to Nirmalkumar Yuvaraj January 19, 2023 01:51 PM UTC

Hi  Nirmalkumar

Thank for the support.


Loader.
Live Chat Icon For mobile
Up arrow icon