So, I have a WPF app which starts up with the MainWindow.xaml and then starts a background thread which cycles through pages for the MainWindow. What the thread really does is sets the content to a new page every 20/30 seconds (if there's a better way to do this as well then I'd gladly appreciate a suggestion). So I've built the app using the MVVM pattern so every page has it's own viewmodel class with corresponding data. Each class as some lists containing data to be displayed in a Datagrid table, and the table is bound to the list. But I want to update the list without freezing the UI, essentially asynchronously or on another thread. How do I go about doing this?
I haven't really come up with any solutions as of yet, I thought about locking the viewmodel while updating it but I feel like that would break the UI in some way.
Viewmodel example
private List<ChangeInfo> nonApprovedChanges;
public ÄrendenStatsViewModel()
{
nonApprovedChanges = new List<ChangeInfo>;
}
public List<ChangeInfo> NonApprovedChanges //this is bound to a datagrid
{
get { return nonApprovedChanges; }
set
{
if (nonApprovedChanges != value)
{
nonApprovedChanges = value;
OnPropertyChange();
}
}
}
Thread that changes slides
private void ManageSlides()
{
new Thread(() =>
{
var page1 = new ExamplePage();
var page2 = new ExamplePage2();
while (true)
{
Dispatcher.Invoke(new Action(() =>
{
Content = page1;
}));
Thread.Sleep(1000 * 20);
Dispatcher.Invoke(new Action(() =>
{
Content = page2;
}
Thread.Sleep(1000 * 30);
}
}).Start();
}
XAML
<Grid>
<Grid.RowDefinitions>
<RowDefinition Width="*" />
<RowDefinition Width="15*" />
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource DataGridTitleStyle}" Grid.Column="0" HorizontalAlignment="Left" Text="Not approved" />
<TextBlock Style="{StaticResource DataGridTitleStyle}" Grid.Column="1" HorizontalAlignment="Right" Text="{Binding NonApprovedChangesCount}" />
</Grid>
<DataGrid x:Name="nonApprovedChangesDataGrid" ItemsSource="{Binding NonApprovedChanges}" Style="{StaticResource DataGridStyle}" />
<DataGrid.Columns>
<DataGridTextColumn Width="3*" HeaderStyle="{StaticResource DataGridHeaderStyle}" Header="Change" Binding="{Binding Changenumber}" />
<DataGridTextColumn Width="4*" HeaderStyle="{StaticResource DataGridHeaderStyle}" Header="Requester" Binding="{Binding Requester}" />
<DataGridTextColumn Width="6*" HeaderStyle="{StaticResource DataGridHeaderStyle}" Header="Date" Binding="{Binding Date}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
I'd like to have a separate thread (similar to the page-slider) that continuously updates the list nonApprovedChanges in the example viewmodel. Although it doesn't have to be a separate thread, I just want a niche way to update the List without freezing the UI.