Building custom controls in WPF can provide you with lots of flexibility.  It allows you to entirely separate the behavior of the control from the look of the control.  This is the premise behind most of what WPF offers.  In this post I will show you how you can build a simple control similar to the search control in Outlook 2007.

 Filter TextBox

Add a new WPF Application project.

New Project

Then add a WPF User Control Library.

Add New Project

Delete the generated UserControl1.xaml that was given to you.

Microsoft Visual Studio

Add a new WPF Custom Control.

Add New Item - FilterTextBox

Your solution should now look like this:

Solution Explorer

 

The template gives you a FilterTextBox.cs and Generic.xaml file.

public class FilterTextBox : Control
{
    static FilterTextBox()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(FilterTextBox),
            new FrameworkPropertyMetadata(typeof(FilterTextBox)));
    }
}

 

The default Generic.xaml is the default look for your custom control, and is found in the Theme directory.  It is just an empty border for now:

<Style TargetType="{x:Type local:FilterTextBox}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type local:FilterTextBox}">
        <Border Background="{TemplateBinding Background}"
                BorderBrush="{TemplateBinding BorderBrush}"
                BorderThickness="{TemplateBinding BorderThickness}">
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

 

Now lets start building the behavior of our control.  We'll start by adding a 'Text' dependency property.  This will be the filter text that the user types in.  Notice that I've created callbacks to be notified when the property has changed.  And as always, do NOT put any code within the getter and setter of the CLR property, because WPF bypasses this property at runtime and calls GetValue and SetValue directly.  However the CLR property is still needed to use the property in xaml.

public static readonly DependencyProperty TextProperty =
    DependencyProperty.Register("Text",
                                typeof(String),
                                typeof(FilterTextBox),
                                new UIPropertyMetadata(null,
                                    new PropertyChangedCallback(OnTextChanged),
                                    new CoerceValueCallback(OnCoerceText))
                               );
 
private static object OnCoerceText(DependencyObject o, Object value)
{
    FilterTextBox filterTextBox = o as FilterTextBox;
    if (filterTextBox != null)
        return filterTextBox.OnCoerceText((String)value);
    else
        return value;
}
 
private static void OnTextChanged(DependencyObject o,
                                  DependencyPropertyChangedEventArgs e)
{
    FilterTextBox filterTextBox = o as FilterTextBox;
    if (filterTextBox != null)
        filterTextBox.OnTextChanged((String)e.OldValue, (String)e.NewValue);
}
 
protected virtual String OnCoerceText(String value)
{
    return value;
}
 
protected virtual void OnTextChanged(String oldValue, String newValue)
{
}
 
public String Text
{
    // IMPORTANT: To maintain parity between setting a property in XAML
    // and procedural code, do not touch the getter and setter inside
    // this dependency property!
    get
    {
        return (String)GetValue(TextProperty);
    }
    set
    {
        SetValue(TextProperty, value);
    }
}    

 

We'll want users of the control to be notified when the text in our TextBox has changed, so lets create a 'TextChanged' event.

public static readonly RoutedEvent TextChangedEvent =
    EventManager.RegisterRoutedEvent("TextChanged",
                                    RoutingStrategy.Bubble,
                                    typeof(RoutedEventHandler),
                                    typeof(FilterTextBox));
 
public event RoutedEventHandler TextChanged
{
    add { AddHandler(TextChangedEvent, value); }
    remove { RemoveHandler(TextChangedEvent, value); }
}

 

Now lets go back and modify our OnTextChanged method to raise our TextChanged event.

protected virtual void OnTextChanged(String oldValue, String newValue)
{
    // fire text changed event
    this.RaiseEvent(new RoutedEventArgs(FilterTextBox.TextChangedEvent, this));
}

 

With the base behavior mostly done, we can move on to creating a generic look for our control.  Lets add a DockPanel with a Button and a TextBox, the Button docked to the right.  Lets also bind the 'Text' property of the TextBox to the 'Text' property of our control.  We want the 'UpdateSourceTrigger' to be 'PropertyChanged' so that the 'TextChanged' event we created will be fired every time the user types something into the TextBox.  Notice that we don't want the TextBox to have a border because then we'd have two borders.

<ControlTemplate TargetType="{x:Type local:FilterTextBox}">
  <Border
      Background="{TemplateBinding Background}"
      BorderBrush="{TemplateBinding BorderBrush}"
      BorderThickness="{TemplateBinding BorderThickness}"
      CornerRadius="3">
    <DockPanel
      LastChildFill="True"
      Margin="1">
      <Button
        x:Name="PART_ClearFilterButton"
        Content="X"
        Width="20"
        ToolTip="Clear Filter"
        DockPanel.Dock="Right" />
      <TextBox
        x:Name="PART_FilterTextBox"
        Text="{Binding Path=Text,
                      Mode=TwoWay,
                      UpdateSourceTrigger=PropertyChanged,
                      RelativeSource={RelativeSource TemplatedParent}}"
        BorderBrush="{x:Null}"
        BorderThickness="0"
        VerticalAlignment="Center" />
    </DockPanel>
  </Border>
</ControlTemplate>

 

Take special note of the names of the controls.  They both begin with 'PART_'.  This is the standard way in WPF to signify controls that need to be replaced if you decide to change the template of the control.  If someone templates your control, you need some way to identify that the types used for your parts need to be ones that your control can use.  You can do this by using the TemplatePart attribute and giving it the name and type of your control parts.

[TemplatePart(Name = "PART_FilterTextBox", Type = typeof(TextBox))]
[TemplatePart(Name = "PART_ClearFilterButton", Type = typeof(Button))]
public class FilterTextBox : Control
{
    ...
}

 

We only want the 'Clear Filter' button to be showing when there is text in the TextBox, so lets create a DataTrigger to accomplish that for us.

<ControlTemplate TargetType="{x:Type local:FilterTextBox}">
  <Border>
    ...
  </Border>
  <ControlTemplate.Triggers>
    <DataTrigger Binding="{Binding Path=Text.Length, ElementName=PART_FilterTextBox}" Value="0">
      <Setter TargetName="PART_ClearFilterButton" Property="Visibility" Value="Collapsed" />
    </DataTrigger>
  </ControlTemplate.Triggers>
</ControlTemplate>

 

Now we want to be able to handle when a user clicks on the 'Clear Filter' button.  You do this by overriding the OnApplyTemplate method.  You can get a reference to your controls by calling GetTemplateChild and passing the name of the control.  When the user clicks the 'Clear Filter' button we just want to remove any text in the TextBox.  We'll use the same strategy to get a reference to the TextBox control.

public override void OnApplyTemplate()
{
    base.OnApplyTemplate();
 
    Button clearFilterButton = base.GetTemplateChild("PART_ClearFilterButton") as Button;
    if (clearFilterButton != null)
    {
        clearFilterButton.Click += new RoutedEventHandler(ClearFilterButton_Click);
    }
}
 
private void ClearFilterButton_Click(Object sender, RoutedEventArgs e)
{
    TextBox textBox = base.GetTemplateChild("PART_FilterTextBox") as TextBox;
 
    if (textBox != null)
    {
        textBox.Text = String.Empty;
    }
}

 

In the WPF Application project add a reference to the custom control project.

Add Reference

Now you can create a namespace for the controls project, labeled as controls here, and add your control to the form.

<Window
    x:Class="FilterTextBoxDemo.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="clr-namespace:FilterTextBox;assembly=FilterTextBox"
    Title="FilterTextBox Demo"
    Height="300"
    Width="300">
  <StackPanel>
    <controls:FilterTextBox />
  </StackPanel>
</Window>

 

And we have a working control!

Filter TextBox Demo 

To make sure that the control still works when templated, lets go ahead and make a simple template for it.

<Window ...>
  <Window.Resources>
    <Style x:Key="LOCAL_MyStyle" TargetType="{x:Type controls:FilterTextBox}">
      <Setter Property="BorderBrush" Value="CornFlowerBlue" />
      <Setter Property="BorderThickness" Value="2" />
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="{x:Type controls:FilterTextBox}">
            <Border
              Background="{TemplateBinding Background}"
              BorderBrush="{TemplateBinding BorderBrush}"
              BorderThickness="{TemplateBinding BorderThickness}"
              CornerRadius="10">
              <DockPanel
                LastChildFill="True"
                Margin="5">
                <Button
                  x:Name="PART_ClearFilterButton"
                  Content="--"
                  Width="30"
                  ToolTip="Clear Filter"
                  DockPanel.Dock="Left" />
                <TextBox
                  x:Name="PART_FilterTextBox"
                  Text="{Binding Path=Text,
                          Mode=TwoWay,
                          UpdateSourceTrigger=PropertyChanged,
                          RelativeSource={RelativeSource TemplatedParent}}"
                  BorderBrush="{x:Null}"
                  BorderThickness="0"
                  VerticalAlignment="Center" />
              </DockPanel>
            </Border>
            <ControlTemplate.Triggers>
              <DataTrigger Binding="{Binding Path=Text.Length, ElementName=PART_FilterTextBox}" Value="0">
                <Setter TargetName="PART_ClearFilterButton" Property="Visibility" Value="Collapsed" />
              </DataTrigger>
            </ControlTemplate.Triggers>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>
  </Window.Resources>
  <StackPanel>
    <controls:FilterTextBox
      BorderBrush="#ACBFE4"
      Margin="10"
      TextChanged="FilterTextBox_TextChanged"/>
    <controls:FilterTextBox
      Style="{StaticResource LOCAL_MyStyle}"
      Margin="10"
      TextChanged="FilterTextBox_TextChanged"/>
  </StackPanel>
</Window>

 

Hope that helps!

Joe

Keith encountered some interesting behavior while trying to build a Custom Task Pane hosting a WPF control in VSTO to use in Excel.  (See my post on "Using WPF With VSTO & Office 2007").

"I click the search textbox and it appears to have focus... but, when I start typing, text goes into the active cell and not the textbox..."

Throwing together a simple control I experienced the same behavior:

Test Addin - Input Focus Non-Activated

Notice that the second TextBox contains the cursor, however the Task Pane "Test Addin" is not highlighted as if it's currently activated, which looks like this:

Test Addin - Input Focus Activated

So what's going on here?  Essentially it appears that the ElementHost is never getting a notification from the WPF message loop that a child control has taken input focus.  Excel is also "greedy" on handling keyboard input if a Task Pane or other control does not have input focus.  Reading this "Windows Forms and WPF Interoperability Input Architecture" MSDN article, it states:

In Windows Forms, keyboard messages are routed to the window handle of the control that has focus. In the ElementHost control, these messages are routed to the hosted element. To accomplish this, the ElementHost control provides an HwndSource instance. If the ElementHost control has focus, the HwndSource instance routes most keyboard input so that it can be processed by the WPF InputManager class.

So lets give the ElementHost focus!  Using the new Routed Event architecture we can have our ElementHost be notified anytime any WPF element that inherits from UIElement has been clicked.  I chose to use a Tunneling strategy to handle the MouseDown event.  The third argument "true" of the AddHandler method says that we want to be notified of ALL MouseDown events, even if another control handles the event and prevents it from continuing on.  You can read about Routed Events (Tunneling & Bubbling) in Adam Nathan's WPF Unleashed book, chapter 3.  (Freely available to download from Time Sneath's blog.)

using Forms = System.Windows.Forms;

 

private ElementHost m_ElementHost;

private CustomTaskPane m_Pane;

private Forms.UserControl m_UserControl;

 

private void ThisAddIn_Startup(Object sender, System.EventArgs e)

{

    m_ElementHost = new ElementHost();

    m_ElementHost.Child = new UserControl2();

    m_ElementHost.Child.AddHandler(

        UIElement.PreviewMouseDownEvent,

        new RoutedEventHandler(PreviewMouseDown_Event),

        true

    );

    m_ElementHost.Dock = Forms.DockStyle.Fill;

    m_UserControl = new Forms.UserControl();

    m_UserControl.Controls.Add(m_ElementHost);

    m_Pane = this.CustomTaskPanes.Add(m_UserControl, "Test Addin");

    m_Pane.Visible = true;

}

 

private void PreviewMouseDown_Event(Object sender, RoutedEventArgs e)

{

    m_ElementHost.Focus();

}

Figure 3.9 (taken from Adam's book) shows the element hierarchy.

WPF Element Hierarchy 

Using this same strategy you could handle only giving the ElementHost, and therefore the Task Pane, focus when say just a TextBox is clicked or got focus, or a Button clicked or got focus.  However I thought using UIElement was a bit more succinct.  Hope that helps!

In this screencast I demonstrate how to build a secure, interoperable service using WSIT (Web Services Interoperability Technologies) and WCF 3.0 (Windows Communication Foundation).  This screencast uses certificates to secure a business to business scenario.  Click the image below to watch the screencast online.  You can double-click the player for full-screen mode.  The player is using Silverlight 1.0.

screencast_Thumb

Download directly:  http://xamlcoder.com/demos/net30/wsitcertificates/screencast.wmv

This is the first screencast I've done, so let me know what you think.  If you'd like to see screencasts on other topics (relating to .NET 3.0 technologies) post your ideas!

Demos Download:  http://xamlcoder.com/joe/downloads/WSITDemos.zip

Links:

NetBeans IDE:  http://netbeans.org

WSIT Dev Site:  https://wsit.dev.java.net/

Glassfish Dev Site:  https://glassfish.dev.java.net/downloads/v2-b50g.html

Java One Lab: Make Java and .NET 3.0 interoperability work with WSIT

Ant Script for Certificates:  CopyV3 script

.NET 3.0 Visual Studio Extensions:  http://www.microsoft.com/downloads/details.aspx?familyid=f54f5537-cc86-4bf5-ae44-f5a1e805680d&displaylang=en

This screencast was recorded using the free desktop recording software, CamStudio, and encoded using Microsoft Expression Media Encoder.

P.S.  I know I refer to WSIT as "Web Services Interoperability Toolkit" instead of "Technologies" - sorry!

At first glance binding a control (such as a ListBox) to a DataSet in XAML may not be apparent.  However all you need to remember is that the column names in a DataSet work very similar to the property names on plain CLR objects.  The trick is where you assign the DataSet to the listbox.  You can't use the ItemsSource property on a ListBox directly, because it expects an object of IEnumerable.  What you want is the DataContext.  This tells the control "Hey, I'm going to be working with this data and databinding with it."  The code below creates a simple DataSet with one table that has two columns: Name and Age, then assigns the DataSet to the DataContext of the ListBox control.

public partial class Window1 : System.Windows.Window

{

    public Window1()

    {

        InitializeComponent();

 

        this.Loaded += Window1_Loaded;

    }

 

    private void Window1_Loaded(Object sender, RoutedEventArgs e)

    {

        this.listBox.DataContext = GetData();

    }

 

    private DataSet GetData()

    {

        DataSet data = new DataSet("MyDataSet");

        DataTable table = data.Tables.Add("MyTable");

        table.Columns.Add("Name", typeof(String));

        table.Columns.Add("Age", typeof(Int32));

 

        for (int i = 0; i < 10; i++)

        {

            DataRow row = table.NewRow();

            row["Name"] = "Name " + (i + 1).ToString();

            row["Age"] = i * 10;

            table.Rows.Add(row);

        }

 

        return data;

    }

}

To be able to see your data in the ListBox you need to set a few properties in the XAML markup.  These are the ItemsSource and the ItemTemplate.  The Binding refers to the data that is currently associated to the DataContext.  So for us to bind to the data in the first table, the Path Tables[0]  is used.  Remember that using {Binding Tables[0]} and {Binding Path=Tables[0]} are synonymous.

<Window x:Class="WindowsApplication1.Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Title="WindowsApplication1" Height="300" Width="300"

    >

 

    <Window.Resources>

 

      <DataTemplate x:Key="tableTemplate">

        <StackPanel Margin="3">

          <DockPanel LastChildFill="True">

            <TextBlock Text="Name:"

                      DockPanel.Dock="Left"

                      Margin="0,0,5,0"

                      />

            <TextBlock Text="{Binding Name}" />

          </DockPanel>

          <DockPanel LastChildFill="True">

            <TextBlock Text="Age:"

                      DockPanel.Dock="Left"

                      Margin="0,0,5,0"

                      />

            <TextBlock Text="{Binding Age}" />

          </DockPanel>

        </StackPanel>

      </DataTemplate>

 

    </Window.Resources>

 

    <Grid>

      <ListBox x:Name="listBox"

              ItemsSource="{Binding Tables[0]}"

              ItemTemplate="{StaticResource tableTemplate}"

              >

      </ListBox>

    </Grid>

 

</Window>

If we were to change the code in the load event to bind directly against the table:

private void Window1_Loaded(Object sender, RoutedEventArgs e)

{

    this.listBox.DataContext = GetData().Tables[0];

}

The markup wound just change to ItemsSource="{Binding}" because the current DataContext has the data you are looking for.  If you only need to bind to one property on a DataSet, you can remove the ItemTemplate and use DisplayMemberPath instead.  Notice that the DataTemplate used for the DataSet looks exactly the same as if we were databinding to a plain CLR object.

When you're all finished it looks like this:

Binding to a DataSet in XAML - WindowsApplication1

Hope that helps!

Hosting Windows Forms controls in Office 2007 Custom Task Pane's is pretty simple, as shown in this MSDN article.  I created a simple addin to display a list of image files in a given folder so that the user can double-click on the file name (in a ListBox) and insert the picture into the document.  With little effort it was simple to instead implement a WPF UserControl to spruce up the addin.  You can download the code here.

Document1 - Microsoft Word

 

You can host WPF Elements using the ElementHost control found in the WindowsFormsIntegration assemly that ships with the .NET 3.0 runtime.  The CustomTaskPane requires a Windows Forms UserControl, so I'm just adding the ElementHost control to a plain Windows Forms UserControl and then passing that UserControl to be created with the CustomTaskPane.

internal void AddTaskPane()

{

    ElementHost host = new ElementHost();

    browser = new ImageBrowserControl();

    host.Child = browser;

    host.Dock = DockStyle.Fill;

 

    browser.PictureSelected += ImageBrowserControl_PictureSelected;

 

    UserControl userControl = new UserControl();

    userControl.Controls.Add(host);

 

    pane = this.CustomTaskPanes.Add(userControl, "Image Browser");

 

    pane.Visible = true;

}

 

Inserting images into a Word document is just as simple, as shown in the following code snippet:

private void ImageBrowserControl_PictureSelected(Object sender, EventArgs<Picture> e)

{

    Object missing = System.Reflection.Missing.Value;

 

    Globals.ThisAddIn.Application.Selection.InlineShapes.AddPicture(

        e.Item.Filename, ref missing, ref missing, ref missing);

}

 

The EventArgs<T> class used in the previous handler is a nice trick to use in conjunction with EventHandler<T>.  A tip from Jean-Paul S. Boodhoo's Blog.

public class EventArgs<T> : EventArgs

{

    private T m_Item;

 

    public EventArgs(T item)

    {

        m_Item = item;

    }

 

    public T Item

    {

        get

        {

            return m_Item;

        }

    }

}

 

public event EventHandler<EventArgs<Picture>> PictureSelected;

 

To create  a Ribbon tab you define a set of XML.  The onAction on the button is an event that you can handle in your codebehind file.

<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" onLoad="OnLoad">

  <ribbon>

    <tabs>

      <tab id="VSTOAddIns" label="Addins" >

        <group id="Group1" label="Helpers" visible ="1">

          <button id="ImageBrowser" label="Insert Image"

          onAction="ImageButtonClick"

          imageMso="ContentControlDate"/>

        </group>

      </tab>

    </tabs>

  </ribbon>

</customUI>

 

Handler for toggling showing / hiding the task pane:

public void ImageButtonClick(Office.IRibbonControl control)

{

    if (!m_ImagePaneExists)

    {

        Globals.ThisAddIn.AddTaskPane();

    }

    else

    {

        Globals.ThisAddIn.RemoveTaskPane();

    }

 

    m_ImagePaneExists = !m_ImagePaneExists;

}

 

 The WPF UserControl styles a simple Picture class, shown below:

public class Picture

{

    private FileInfo m_FileInfo;

 

    public Picture(String filename)

    {

        m_FileInfo = new FileInfo(filename);

    }

 

    public String Filename

    {

        get { return m_FileInfo.FullName; }

        set { m_FileInfo = new FileInfo(value); }

    }

 

    public String Name

    {

        get { return m_FileInfo.Name; }

    }

}

 

 DataTemplate for the Picture class:

<DataTemplate DataType="{x:Type local:Picture}">

  <StackPanel MinHeight="0px" MinWidth="0px" MaxHeight="150px" MaxWidth="150px" >

    <Image Stretch="UniformToFill" Source="{Binding Filename}" />

    <TextBlock Text="{Binding Name}"

              FontWeight="Bold"

              HorizontalAlignment="Center"

              />

  </StackPanel>

</DataTemplate>

 

The ListBox style is taken from my previous blog post on styling ListBoxItem's.

<Style TargetType="ListBoxItem">

  <Setter Property="Template">

    <Setter.Value>

      <ControlTemplate TargetType="ListBoxItem">

        <Border x:Name="ItemBorder"

                BorderBrush="Black"

                Background="LightGray"

                BorderThickness="2"

                CornerRadius="4"

                Margin="3"

                >

          <ContentPresenter Margin="2" />

        </Border>

        <ControlTemplate.Triggers>

          <Trigger Property="IsSelected" Value="True">

            <Setter TargetName="ItemBorder"

                    Property="BorderBrush"

                    Value="Red"

                    />

          </Trigger>

          <Trigger Property="IsMouseOver" Value="True">

            <Setter TargetName="ItemBorder"

                    Property="BorderBrush"

                    Value="Blue"

                    />

          </Trigger>

          <MultiTrigger>

            <MultiTrigger.Conditions>

              <Condition Property="IsMouseOver" Value="False" />

              <Condition Property="IsSelected" Value="False" />

            </MultiTrigger.Conditions>

            <Setter TargetName="ItemBorder"

                    Property="Opacity"

                    Value="0.50"

                    />

          </MultiTrigger>

        </ControlTemplate.Triggers>

      </ControlTemplate>

    </Setter.Value>

  </Setter>

</Style>

 

A couple things to remember when building Word Addins is that all Assembly's that you use need to be signed and granted full-trust by the .NET runtime for Word to load them.  Other than that creating Word Addins is pretty simple!

Recently I needed to query an excel file and import that data into a database.  I could not immediately recall how to accomplish this, so with a bit of searching I found the connection settings that I needed.  Bellow is a code snippet that can be used to load all of the data in a workbook into a GridView on an ASP.NET page.  Note the use of the "Extended Properties='Excel 8.0;'" in the connection template as well as Sheet1$ in the SQL command to specify the name of the workbook in the worksheet.

using System;

using System.Data;

using System.Data.OleDb;

using System.Web.UI;

 

public partial class _Default : Page

{

    protected void Page_Load(Object sender, EventArgs e)

    {

        GridView1.DataSource = GetProductData();

        GridView1.DataBind();

    }

 

    private DataSet GetProductData()

    {

        String connectionTemplate = @"Provider=Microsoft.Jet.OLEDB.4.0;" +

            "Data Source={0}; Extended Properties='Excel 8.0;'";

 

        using (OleDbConnection connection = new OleDbConnection(

                String.Format(connectionTemplate,

                              Server.MapPath("~/App_Data/Products.xls"))

              ))

        {

            OleDbCommand command = new OleDbCommand(

                "Select * FROM [Sheet1$]", connection

            );

 

            OleDbDataAdapter adapter = new OleDbDataAdapter(command);

 

            DataSet dataSet = new DataSet();

 

            adapter.Fill(dataSet);

 

            return dataSet;

        }

    }

}

More Posts Next page »