Reputation: 2070
I have a WPF C# datagrid that is read only, its contents are loaded from an external XML file and other forms manipulate the XML file by adding, editing and removing data.
I would like the datagrid to reload when a change is made, however there doesn't appear to be an easy way of doing this.
I intend on putting a 'refresh' of some sort when the 'editing' form closes.
I have tried datagrid.items.refresh()
without success among a few other bits of failed code. (learning C#/WPF)
How am I supposed to do this?
XAML:
<Grid.DataContext>
<XmlDataProvider Source="E:\downloader\downloadConfig.xml" XPath="/download/downloadItem"></XmlDataProvider>
</Grid.DataContext>
<DataGrid x:Name="downloadList" Height="191" VerticalAlignment="Top" ItemsSource="{Binding}" AutoGenerateColumns="False" AlternatingRowBackground="Gainsboro" IsReadOnly="True" DataContext="{Binding}" IsSynchronizedWithCurrentItem="True">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding XPath=ID}" Width="50"></DataGridTextColumn>
<DataGridTextColumn Header="Name" Binding="{Binding XPath=Name}" Width="350"></DataGridTextColumn>
<DataGridTextColumn Header="Status" Binding="{Binding XPath=Status}" Width="100"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
Upvotes: 0
Views: 1123
Reputation: 6850
Bind the DataGrid to a collection that implements the INotifyCollectionChanged interface. Objects that implement this interface will raise events when their contents change, and DataGrid will listen for these events and update itself accordingly.
There is a built-in generic class, ObservableCollection, which takes care of all of this for you. It's usually easiest to just use it. It does have one gotcha, though, which is that it can only be modified from the main thread. If you need to modify it from another thread, use Dispatcher.Invoke (or BeginInvoke) to avoid getting exceptions.
Note that these only notify of 'row-level' changes - the addition, removal, replacement of entire objects from the collection. To have the DataGrid also update itself when objects within the collection change, implement INotifyPropertyChanged on them.
I realize this means a bunch of extra coding since you'll need to implement classes to go between the XML and the collection, but it is the preferred option. On the upside, it should perform better. The DataGrid will be able to only update the rows it needs to update, rather than completely redrawing itself (which can be an expensive operation in WPF).
Upvotes: 1