JadedEric
JadedEric

Reputation: 2083

Field as ObservableCollection gets cleared when property is cleared

I'm relatively new to XAML / Xamarin and I'm running into something I'm hoping someone can help me clarify.

I know the title is misleading, but I couldn't put it any different.

I have the following property in my ViewModel:

private ObservableCollection<Schedule> _scheduleList;
public ObservableCollection<Schedule> ScheduleList
{
    get
    {
        return _scheduleList;
    }

    set
    {
        value = _scheduleList;
    }
}

Somewhere down the line, I do something like this:

private void DayFilter(string week)
{
    try
    {
        var list = _scheduleList.Where(x => x.ScheduleDate.DayOfWeek.ToString() == week);

        ObservableCollection<Schedule> newlist = new ObservableCollection<Schedule>(list);

        ScheduleList.Clear(); // <- this line clears out _scheduleList as well

        foreach (var item in newlist)
        {
            ScheduleList.Add(item);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

Whenever ScheduleList.Clear() is called, it also clears out _scheduleList which is the private field.

I know this has something to do with the fact that this is ObservableCollection, but the requirement is that it should be, and I could not find a way to retain the value on _scheduleList, as I need this field populated throughout the lifetime of the application.

Is there away that the field _scheduleList does not get cleared out?

Upvotes: 0

Views: 78

Answers (1)

Jason
Jason

Reputation: 89117

This is just how C# works

ScheduleList.Clear();

returns a reference to _scheduleList (that's what the public get does) and then calls Clear on it.

In your scenario, you probably need to maintain two completely separate copies of your data - the original, as well as one that you use for filtering/displaying the data.

Upvotes: 5

Related Questions