Blog Stats
  • Posts - 1
  • Articles - 0
  • Comments - 0
  • Trackbacks - 0

 

Saturday, October 31, 2009

WPF 2 way data binding


As I was learning WPF and the new charting controls, I was impressed with how easy and powerful 2-way data binding is with WPF.  In this example, I created a DataGrid and a Chart and bound them to the same DataTable, via the DefaultView property.  The result is that you can edit the DataGrid and see an instant change in the Chart.  Even more impressive is the rubber band effect of the Chart control.  When the Chart is updating, you see the line slowly more to the new location.  Real cool!

Here is the Chart and DataGrid.  By default, the DataGrid is editable and any changes will automatically be updated in the Chart.  Note that I edited row 5 and changed the 5 to a 7 and the Grid location moved.

 

Here is the code :

DataTable table = GetTableNumbers(0);

DataGrid1.ItemsSource = table.DefaultView;

LineSeries1.ItemsSource = table.DefaultView;

//Add a second series just for fun.

DataTable table2 = GetTableNumbers(5);

LineSeries2.ItemsSource = table2.DefaultView;

And the XAML for a Chart and DataGrid:

<Grid>
        <toolkit:DataGrid Name="DataGrid1" Loaded="dgMain_Loaded"                                         AutoGenerateColumns="True"  Margin="386,57,12,12">           
        </toolkit:DataGrid>
        <chartingToolkit:Chart Name="chartVoltageCurrent"
                        Title="Voltage Current" HorizontalAlignment="Left" Width="380" Margin="0,57,0,0">
            <chartingToolkit:LineSeries Name="LineSeries1"
                                        IndependentValuePath="Current"
                                        DependentValuePath="Voltage"
                                        Title="Dev1">
            </chartingToolkit:LineSeries>                    
            <chartingToolkit:LineSeries Name="LineSeries2"
                                        IndependentValuePath="Current"
                                        DependentValuePath="Voltage"
                                        Title="Dev2">             
            </chartingToolkit:LineSeries>
            <chartingToolkit:Chart.Axes>
                <!-- Shared axis -->
                <chartingToolkit:LinearAxis
                                Orientation="X"
                                Title="Current"/>
                <chartingToolkit:LinearAxis
                                Orientation="Y"
                                Title="Voltage"/>
            </chartingToolkit:Chart.Axes>          
        </chartingToolkit:Chart>
    </Grid>
WPF Binding is very powerful and hopfully this simple example gives you an idea of how dynamic you can make applications will little effort. 
-Bill

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
 

 

Copyright © BillSontag