call ObservableCollection get accessor again in code behind

Is it possible to call the ObservableCollection get method again? i need change ItemsSource based on ComboBox selection so i need call my ObservableCollection again this is my code

ObservableCollection<string> sampleData = new ObservableCollection<string>();
public ObservableCollection<string> SampleData
{
    get
    {
        if (sampleData.Count < 1)
            sampleData.Add(line);  

        return sampleData;
    }
}

above code run once when application luanch, but i need call it when combobox changed

private void CmbFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    switch (cmbFilter.SelectedIndex)
    {
        case 0:         
            break;
        case 1:
            break;
        case 2:
            break;
        case 3:
            break;
    }
}

1 answer

  • answered 2019-02-10 21:30 Bijington

    The whole point of an ObservableCollection is that you do not need to implement what you are suggesting in your SampleData getter. There are 2 approaches you could take here:

    Make use of ObservableCollection

    Note there are better options here but out of scope of the question. Lookup up SelectedItem bindings for a ComboBox.

    private void CmbFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        // Modify your collection here based on what was selected.
    }
    

    Forget about ObservableCollection

    This approach will require you to implement INotifyPropertyChanged on your ViewModel class.

    public IEnumerabe<string> SampleData
    {
        get
        {
            // Return values based on the selection.
            if (SelectedData == "FirstValueICareAbout") // SelectedData assumes you have investigated how to bind to the SelectedItem of a ComboBox.
            {
                return new[]
                {
                    "FirstValue",
                    "SecondValue"
                };    
            }
    
            return Enumerable.Empty<string>();
        }
    }
    
    private void CmbFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        // Notify the UI that SampleData has changed using INotifyPropertyChanged implementation.
        RaiseNotifyPropertyChanged(nameof(SampleData));
    }