i dont really understand why and what happens in the background, so please help me with it.
I have a simple ListView:
<ListView Height="100" HorizontalAlignment="Left" Margin="67,84,0,0" ItemsSource="
{Binding Path=ListBinding}" Name="listView1" VerticalAlignment="Top" Width="351" />
and a Button:
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="162,41,0,0"
Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
And I set the datacontext to my “viewmodel” class:
InitializeComponent();
this.DataContext = new VM1();
now, if i initialise the obscollection in the VM1’s constructor, the binding works, when i populate the ListBinding with the button1_click function:
private void button1_Click(object sender, RoutedEventArgs e)
{
(this.DataContext as VM1).Do();
}
public VM1()
{
ListBinding = new ObservableCollection<string>();
}
public void Do()
{
ListBinding.Add("VM1 works 1");
ListBinding.Add("VM1 works 2");
}
But if i initialize it in the Do() function, it doesnt:
public VM1()
{ }
public void Do()
{
ListBinding = new ObservableCollection<string>();
ListBinding.Add("VM1 NOT works 1");
ListBinding.Add("VM1 NOT works 2");
}
I guess the answer to this might be a one liner, and i wanna understand the “why”.
thanks!
You did not list the code for the ListBinding property.
The property setter must call NotifyOfPropertyChange so the binding will get updated.
ObservableCollection automatically updates with the CONTENTS of the list change, not the entire list object.
Hope that helps.
Edit: here is the code for the property: