Dynamic UI with WPF and LINQ

Dynamic UI with WPF and LINQ

  • Comments 42

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
End Class

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:

ColumnName
DataType
MaxLength
IsPrimaryKey

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:

CREATE PROCEDURE dbo.GetTableSchema
    (
    @table varchar(50)
    )    
AS
SELECT 
c.table_name As TableName, 
c.column_name As ColumnName, 
c.data_type As DataType, 
c.character_maximum_length As MaxLength,
    COALESCE (
    ( SELECT 
        CASE cu.column_name
            WHEN null THEN 0
            ELSE 1
        END
    FROM information_schema.constraint_column_usage cu
    INNER join information_schema.table_constraints ct
    ON ct.constraint_name = cu.constraint_name
    WHERE 
    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"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1"  Name="Window1" SizeToContent="WidthAndHeight" >
    <Grid Name="MainGrid"  >
        <Grid.RowDefinitions>
            <RowDefinition Height="10*" />
            <RowDefinition Height="60*" />
        </Grid.RowDefinitions>
        <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>
        </StackPanel>
        <ContentControl Grid.Row="1" Name="DynamicContent" Margin="3" />
    </Grid>
</Window>

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"
                     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
                     <Grid.ColumnDefinitions>
                         <ColumnDefinition Width="100*"/>
                         <ColumnDefinition Width="200*"/>
                     </Grid.ColumnDefinitions>
                     <StackPanel Name="StackLabels" Margin="3">
                         <%= From column In customerSchema _
                             Where column.IsPrimaryKey = 0 _
                             Select <Label
                                        Height="28"
                                        Name=<%= column.ColumnName & "Label" %>
                                        HorizontalContentAlignment="Right">
                                        <%= column.ColumnName %>:</Label> %>
                     </StackPanel>
                     <StackPanel Grid.Column="1" Name="StackFields" Margin="3">
                         <%= From column In customerSchema _
                             Where column.IsPrimaryKey = 0 _
                             Select GetUIElement(column) %>
                     </StackPanel>
                 </Grid>

        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
                           Height="28"
                           Name=<%= "txt" & column.ColumnName %>
                           Text=<%= "{Binding Path=" & column.ColumnName & ", ValidatesOnDataErrors=True}" %>/>
            Case "bit"
                Return <CheckBox
                           HorizontalContentAlignment="Left"
                           Name=<%= "chk" & column.ColumnName %>
                           IsChecked=<%= "{Binding Path=" & column.ColumnName & ", ValidatesOnDataErrors=True}" %>>
                           <%= column.ColumnName %>
                       </CheckBox>
            Case Else
                Return <TextBox
                           Height="28"
                           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
        Else
            Me.DataContext = Nothing
        End If
    End Sub

    Private Sub btnSave_Click() Handles btnSave.Click
        If Me.DataContext IsNot Nothing Then
            Try
                db.SubmitChanges()
                MsgBox("Saved")

            Catch ex As Exception
                MsgBox(ex.ToString)
            End Try
        End If
    End Sub
End Class

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.

Enjoy!

Leave a Comment
  • Please add 5 and 1 and type the answer here:
  • Post
  • Hi Minh,

    TableName = varchar(50) (String)

    ColumnName = varchar(50) (String)

    DataType = varchar(25) (String)

    MaxLength = int (Integer)

    IsPrimaryKey = int (Integer)

    HTH,

    -B

  • Hi Beth, I just saw this and I'm amazed! I had no idea you could do this in VB, I mean, use xaml directly in code! Please tell if there is any way to acheive this in C#.

    Thanks!

  • Hi Jason,

    You can't specify event handlers in the dynamic XAML because it must be compiled. However you can hook up the event in code. Here's a blog post from Calvin on the team that shows you how.

    http://blogs.msdn.com/calvin_hsia/archive/2007/11/28/6583391.aspx

    HTH,

    -B

  • Thanks,

    That was exactly what I was looking for.

    Jas

  • Hi Bruno,

    XML Literals are only supported in VB. However you can use the LINQ to XML api directly to manually construct the XAML it's just not as easy.

    -B

  • How do you translate the following into c#?

    Imports <xmlns="http://schemas.microsoft.com/winfx/2006/

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

    Thanks,

    Doug

  • Hey Beth,

    Thx for the help on my last question.  That fixed the issue.  Now i have another question.  I am getting a type cast exception on "Dim customerSchema = db.GetTableSchema("Customers").ToList()".  The exception is says "Unable to cast object of type 'System.Int32' to type 'System.String'".  I have tried copy and pasting your code, thinking that i missed something but even yours is casting the same error.  I have even redone the stored prodecure thing that was the issue but i cant figure it out.  Any thoughts?

    Thx

    G

  • Hi Beth,

    WPF and Linq are cool!

    I am having the same issue than Greg.

    The line below:

    Dim customerSchema = db.GetTableSchema("Customers").ToList()

    Produces the following error:

    Unable to cast object of type 'System.Int32' to type 'System.String'.

    Please help and thanks for all your efforts.

    G

  • Hi Greg/Gonzalo,

    When you create the TableSchema class you need to make sure each of the properties you are mapping are the correct type. The MaxLength and IsPrimaryKey are both Integers.

    HTH,

    -B

  • Hi Beth,

    Thx again for the help.  I did correct the properties for the table but that still did not fix it.  I then had to delete both the table and stored produced reference in the Northwind.dbml and re-add them, as the steps document.  After doing so, it worked.  Thx Beth for the work and help, this great!

    G

  • ¡Perfecto!

    Magnifico. Thanks Beth. I was about to say that after making sure the properties were correct it worked!

    Mucho más for favor? Keep WPFing with Linq please ;)

    Bravo

    G

  • MSBuild MSBuild Reserved Properties [Via: Sayed Ibrahim Hashimi ] Sharepoint Adding Copy and Paste...

  • Hi Beth,

    I did some of this, but  I had made my own table, because I don't have northwind loaded anywhere.  The beginning stuff worked fine, but when you got in to the depths of the code, there were fields that appeared to be dependent on that particualar table or database.

    Would like to work some more on it over the weekend, if you would be so kind as to provide a link to where I can download the version of it that you have, it would be appreciated.

    Thanks,

    John aka Radiolistener

  • In my last post on this subject I explored creating WPF UI's dynamically using XML literals. The one

  • Hi John (Radiolistener),

    I just uploaded the sample onto Code Gallery: http://code.msdn.microsoft.com/dynamicWPF

    Enjoy,

    -B

Page 2 of 3 (42 items) 123