Dynamic UI with WPF and LINQ

Lately I’ve been getting my hands deep into WPF with my line-of-business (LOB)/data-based application mind set. I’m taking a different approach to the technology resisting the urge to put on my amateur-designer hat and instead purely focus on data, data-binding, formatting controls, and some basic layout. (Yes before you ask, I have started producing the WPF forms over data videos!)

Today I wanted to play with dynamically creating XAML and loading it at runtime. This was really easy using XML literals and XML namespace imports. Let me show you what I mean. You can load and save XAML at runtime using the System.Windows.Markup.XamlReader and System.Windows.Markup.XamlWriter classes. Create a new WPF project and in the Window1 code-behind you can do this:

Imports <xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation>
Imports <xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml>
Imports System.Windows.Markup

Class Window1

Private Sub Window1_Loaded() Handles MyBase.Loaded

Dim UI = <Label Name=Label1>This is COOL!</Label>

Me.Content = XamlReader.Load(UI.CreateReader())

End Sub

When we run it:

There are a lot of possibilities here. For instance, wouldn’t it be nice to automatically generate all your maintenance screens in your business apps? When I say “maintenance” I mean all those simpler lookup data tables or contact tables. Even a customer contact form is usually pretty basic. Instead of handing those screens to the newbie or the junior on the team why not just generate them all at runtime based on your object model or database schema?

Admittedly this isn’t something that is only unique to WPF. You could do this in Winforms as well but it was an exercise in coding the layout by hand. WPF makes this a breeze because we can define one piece of XAML and we can construct it from a single LINQ query. You can use reflection to look at your object model but if it’s really simple and maps one-to-one to your database table anyway you can just create a table (or a stored proc) that contains the schema (or meta-data) of all of your maintenance tables. For instance to generate a simple UI we would probably want to obtain at minimum the following properties for each column in a table:


You can either create a meta-data table in your database or a stored proc that returns the info from the information schema (check permissions for the stored proc if you go that route). I was playing with the stored proc idea because then if I make a change to my database, I don’t need to update my code necessarily. So for this example I created a stored proc in the Northwind database called GetTableSchema:

@table varchar(50)
c.table_name As TableName,
c.column_name As ColumnName,
c.data_type As DataType,
c.character_maximum_length As MaxLength,
CASE cu.column_name
WHEN null THEN 0
FROM information_schema.constraint_column_usage cu
INNER join information_schema.table_constraints ct
ON ct.constraint_name = cu.constraint_name
ct.constraint_type = ‘PRIMARY KEY’
AND ct.table_name = c.table_name
AND cu.column_name = c.column_name
),0) AS IsPrimaryKey
FROM information_schema.columns c
INNER JOIN information_schema.tables t
ON c.table_name = t.table_name
WHERE @table = t.table_name and
(t.table_type = ‘BASE TABLE’ and not
(t.table_name = ‘dtproperties’) and not
(t.table_name = ‘sysdiagrams’))
ORDER BY c.table_name, c.ordinal_position

I then added a new “LINQ to SQL classes” item to my project and dragged Customer onto the design surface (for this example that’s what we’ll be editing) from the Northwind database I had connected to in my Server Explorer. I then expanded the “Stored Procedures” and dragged the above procedure onto the methods pane. Next I manually created an object on the design surface called TableSchema that contained the same properties as the fields I’m returning from the stored proc. Once I have that all set up I can now map the result type of the stored proc to the TableSchema class:

Okay now that we have that set up we can get back to the fun stuff. I created a simple lookup textbox and “Find” and “Save” buttons at a fixed area at the top of my WPF window. Under that I dragged a ContentControl onto the form and named it DynamicContent. We’re going to generate the content here from the Customer schema and bind to the customer object that is returned from our LINQ query when we click find.

<Window x:Class=”Window1″
Title=”Window1″ Name=”Window1″ SizeToContent=”WidthAndHeight” >
<Grid Name=”MainGrid” >
<RowDefinition Height=”10*” />
<RowDefinition Height=”60*” />
<StackPanel Name=”StackPanel1″ Orientation=”Horizontal” Margin=”3″ VerticalAlignment=”Top”>
<Label Height=”28″ Name=”Label1″ Width=”84″ HorizontalContentAlignment=”Right” FontWeight=”Bold”>ID</Label>
<TextBox Height=”25″ Name=”txtSearch” Width=”120″>ALFKI</TextBox>
<Button Height=”25″ Name=”btnFind” Width=”75″>Find</Button>
<Button Height=”25″ Name=”btnSave” Width=”75″>Save</Button>
<ContentControl Grid.Row=”1″ Name=”DynamicContent” Margin=”3″ />

First let’s generate the UI in the Load event of our form. The first thing is to add the appropriate Imports at the top of the file and then we can generate our UI. (I also have handlers here for the actual loading and saving of the customer.)

Imports <xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation>
Imports <xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml>
Imports System.Windows.Markup

Class Window1

Dim db As New NorthwindDataContext
Dim CustomerData As Customer

Private Sub Window1_Loaded() Handles MyBase.Loaded

Dim customerSchema = db.GetTableSchema(“Customers”).ToList()

Dim UI = <Grid xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
<ColumnDefinition Width=100*/>
<ColumnDefinition Width=200*/>
<StackPanel Name=StackLabels Margin=3>
<%= From column In customerSchema _
Where column.IsPrimaryKey = 0 _
Select <Label
Name=<%= column.ColumnName & “Label” %>
<%= column.ColumnName %>:</Label> %>
<StackPanel Grid.Column=1 Name=StackFields Margin=3>
<%= From column In customerSchema _
Where column.IsPrimaryKey = 0 _
Select GetUIElement(column) %>

Me.DynamicContent.Content = XamlReader.Load(UI.CreateReader)

End Sub

Private Function GetUIElement(ByVal column As TableSchema) As XElement
Select Case column.DataType
Case “datetime”, “int”
Return <TextBox
Name=<%= “txt” & column.ColumnName %>
Text=<%= “{Binding Path=” & column.ColumnName & “, ValidatesOnDataErrors=True}” %>/>
Case “bit”
Return <CheckBox
Name=<%= “chk” & column.ColumnName %>
IsChecked=<%= “{Binding Path=” & column.ColumnName & “, ValidatesOnDataErrors=True}” %>>
<%= column.ColumnName %>
Case Else
Return <TextBox
Name=<%= “txt” & column.ColumnName %>
MaxLength=<%= column.MaxLength %>
Text=<%= “{Binding Path=” & column.ColumnName & “, ValidatesOnDataErrors=True}” %>/>
End Select
End Function

Private Sub btnFind_Click() Handles btnFind.Click
If Me.txtSearch.Text <> “” Then
Me.CustomerData = (From cust In db.Customers _
Where cust.CustomerID = Me.txtSearch.Text).FirstOrDefault()

Me.DataContext = Me.CustomerData
Me.DataContext = Nothing
End If
End Sub

Private Sub btnSave_Click() Handles btnSave.Click
If Me.DataContext IsNot Nothing Then

Catch ex As Exception
End Try
End If
End Sub

The stored proc will work for any table contained in the database, so we could even abstract this further, and I obviously didn’t get very fancy with the UI — but I think you get the idea.

UPDATE: Read the latest post on dynamic data entry and download the code samples.