I’m experimenting with databinding in WPF
I have this datagrid that is bound to a mysql view, it’s gonna be read only, but I’d like it to automatically refresh when changes are made to the database.
Couldn’t find anything useful on google and I have no idea where to start.
This is the dataprovider class.
class ConDataProvider
{
private MySqlDataAdapter adapter;
private Data data;
private DataTable table;
public ConDataProvider(string query)
{
data = new Data();
table = new DataTable("con_FullGrid");
adapter = data.getAdapter(query);
adapter.Fill(table);
}
public DataView GetDView()
{
dv = new DataView();
dv.Table = table;
return dv;
}
}
And the XAML for the window
<Window x:Class="HelioWPF_Alpha01.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:local="clr-namespace:HelioWPF_Alpha01"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="676" Width="924" MinHeight="300" MinWidth="463" Background="{x:Null}">
<Window.Resources>
<ObjectDataProvider x:Key="ConDataProvider" ObjectType="{x:Type local:ConDataProvider}">
<ObjectDataProvider.ConstructorParameters>
<sys:String>SELECT * FROM con_FullGrid</sys:String>
</ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>
<ObjectDataProvider x:Key="btable" ObjectInstance="{StaticResource ConDataProvider}"
MethodName="GetDView"/>
</Window.Resources>
<Grid Name="mainGrid" DataContext="{Binding Source={StaticResource btable}" KeyDown="mainGrid_KeyDown" FlowDirection="LeftToRight" >
<DataGrid AutoGenerateColumns="True" ItemsSource="{Binding}" Name="dataGrid1" FrozenColumnCount="20" RowHeight="25" Grid.ColumnSpan="4" ColumnWidth="*" MouseDoubleClick="dataGrid1_MouseDoubleClick" SelectionMode="Single" Grid.Row="2" Grid.Column="1" TabIndex="1" GotKeyboardFocus="dataGrid1_GotKeyboardFocus">
<DataGrid.AlternatingRowBackground>
<LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
<GradientStop Color="Black" Offset="0" />
<GradientStop Color="#16436DF8" Offset="0" />
</LinearGradientBrush>
</DataGrid.AlternatingRowBackground></DataGrid>
</Grid>
What I have been doing is kind of faking it by reinitializing the ConDataProvider class in behind code and rebinding the datagrid on various events.
But it’s an ugly hack.
I wouldn’t mind redesigning the whole thing if I have to.
The Data class just contains the connection string and some methods to interact with the database.
You can see it here: http://pastebin.com/m9HLfwEQ
Thanks in advance.
Hope to get some good tips.
How about if you wire up some Reactive Extensions.
What you could do is create an observable that polls your DB every X seconds. Then have your Observer connect to that observable. In the OnNext event of the Observer, you could add the data to your grid, or rebind, whatever.
Essentially, you’d be creating something that sits between your database and your app that listens for changes and pushes those changes to you.