Tuesday, 17 June 2008

Using Windows Form Control in WPF

Interesting enough that WPF does not have DateTimePicker (or Calendar). So we have decided to use the Windows Form DateTimePicker for now (just for now). Using a Windows Form control in WPF is not hard at all. :)

First of all, add a Grid to wherever you want your control to be:

    <Grid Height="28" Margin="116,0,0,49"
Name="DateGrid" VerticalAlignment="Bottom"
HorizontalAlignment="Left" Width="195">
</Grid>

Then add References to System.Windows.Forms and WindowsFormsIntegration and using:

using System.Windows.Forms.Integration;
using System.Windows.Forms;

Now, in your Window/UserControl Loaded event handler, create the Windows Forms Control and add it to the grid - by first adding it to WindowsFormsHost.

private void Window_Loaded(object sender, RoutedEventArgs e)
{
WindowsFormsHost host = new WindowsFormsHost();
DateTimePicker dateTimePicker = new DateTimePicker();
dateTimePicker.Width = (int)this.DateGrid.Width;
host.Width = (int)this.DateGrid.Width;
host.Child = dateTimePicker;
this.DateGrid.Children.Add(host);
}

That's it!

3 comments:

  1. Xceed includes a free WPF DateTimePicker / Calendar control along with our free datagrid. (xceed.com)

    ReplyDelete
  2. Yeah, and Jimmy from your side was supposed to send me one + a free license to test that out and give you guys feedback. Guess he completely forgotten. :D

    ReplyDelete
  3. Thanks for the tips. It got me started.

    With the knowledge gained, I tried to get it working declaratively which I did. So, I'd share this back to you.

    1) Add references of form and window host
    2) Declare the control and the window host
    e.g.
    xmlns:host="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
    3) Now declare the control inside the host element

    Hope this help

    ReplyDelete