I'm a bit confused with the WPF data binding. I've tried a lot of examples, but I think I'm not understanding the basics of this topic.
I have the following datagrid, binded to an ObservableCollection(Of T), where T class has a Name attribute which is shown in the datagrid column. My T class also implements the INotifyPropertyChanged and fires the event properly when the Name property changes.
<DataGrid Grid.Row="1" Name="MyDataGrid" AutoGenerateColumns="False" ItemsSource="{Binding}" >
<DataGrid.Columns>
<DataGridTextColumn x:Name="NameColumn" Header="Name" Binding="{Binding Name}" />
</DataGrid.Columns>
</DataGrid>
Then, in the code-behind class, I have the underlying collection which is feeding the datagrid.
public ObservableCollection<T> MyCollection
{
get;
set;
}
Finally, when my application starts, I load the "MyCollection" property and tell the datagrid to use that collection.
public void InitApp()
{
MyCollection = [... taking data from somewhere ...];
MyDataGrid.ItemsSource = MyCollection;
}
This is all working fine (the data is shown properly). But then, if I reload the collection (taking again completely different data from somewhere), if I do not execute again the MyDataGrid.ItemsSource = MyCollection; instruction, the datagrid is not updated.
I think it's not a good practise using the XXX.ItemsSource = YYY every time I reload data, so that I guess I'm doing something wrong. In some examples I saw that the XAML DataGrid is binded like:
<DataGrid ItemsSource="{Binding CollectionName}">
...
</DataGrid>
that I guess is aimed at using that collection, so that there's no need to do .ItemsSource programmatically... but I could not make it run.
Can anyone show me the light at the end of the tunnel?