0

In my solution I use specific class which contains a collection of some elements. When I want to Binding this collection I usually use a such path {Binding MyClass.InnerCollection}. It works fine before that moment when I will try to set another instance for that class, and than it's could not be binded.

Question: How to reset the source and keep the binding possible. Is it possible to reset the source without losing the binding without changing ItemsSource directly?

XAML

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <ListView ItemsSource="{Binding Container.InnerCollection}"/>

    <StackPanel Grid.Column="1">
        <Button Content="Add new item" Click="AddNewItem"/>
        <Button Content="Reset source" Click="ResetSource"/>
    </StackPanel>
</Grid>

C#

public partial class MainWindow : Window, INotifyPropertyChanged
{

    public MainWindow()
    {
        Container = new MyClass() { InnerCollection = new ObservableCollection<string>() { "Start" } };

        this.DataContext = this;
        InitializeComponent();
    }
    public MyClass Container { get; set; }

    public void AddNewItem(object sender, RoutedEventArgs e)
    {
        Container.InnerCollection.Add($"AddedItem");
    }
    public void ResetSource(object sender, RoutedEventArgs e)
    {
        Container = new MyClass() { InnerCollection = new ObservableCollection<string>() { $"Reseted" } };
    }
}

public class MyClass
{
    public ObservableCollection<string> InnerCollection { get; set; }
}
Cobret
  • 34
  • 4

1 Answers1

0

Let's reset only what you need to reset:

public void ResetSource(object sender, RoutedEventArgs e)
{
    Container.InnerCollection = new ObservableCollection<string>() { $"Reseted" };
}
Roman Ryzhiy
  • 1,540
  • 8
  • 5