Archive for the ‘Custom Controls’ Category.

How To Animate a Changing Property in a Custom Control in Silverlight

For my recent visualization, I created a custom control in Silverlight that animated the color of a Path every time a “Fill” property on the control was changed. I thought I would pass along my learning from this process.

First thing I learned was that you cannot use TemplateBinding in a Storyboard (I think). I asked this question on Stack Overflow and I haven’t gotten an answer. But I’m pretty sure that in Silverlight you cannot use TemplateBinding to attach a property to a KeyFrame value. This means that you have to have a pointer in the control code the allows access to the KeyFrame so you can update the value.

I’ll walk through the conceptual part of animating a property in a Custom Control in Sivlerlight and then walk through the code to it.

Step 1: Create a PART to your control to hold the Storyboard and a PART to hold the KeyFrame you want to manipulate

I cover how to make a PART to your control here because it was too much to put into a single blog post. You’re going to want to make your Storyboard a PART that is accessed via resources (via MyControlName.Resources[MyStoryboardName]) and your KeyFrame should be a PART that is accessed the normal way (via the GetTemplateChild(MyKeyFrameName) method).

Step 2: Create the DependencyProperty you want to drive the animation

Yet another chance for me to endlessly flog Robby Ingebretsen’s awesome Silverlight Code Snippets. If you use these, use ‘sldpc’, which is the DependencyProperty with a property changed callback. We want to manually fire the animation when the property changes, so we’re going to do that in the callback.

If you don’t want to use Robby’s stuff, here’s the code for a DependencyProperty with a property changed callback. Because my visualization animates the color, I called my property “Fill”.

public SolidColorBrush Fill
{
    get { return (SolidColorBrush)GetValue(FillProperty); }
    set { SetValue(FillProperty, value); }
}

public static readonly DependencyProperty FillProperty =
    DependencyProperty.Register("Fill", typeof(SolidColorBrush), typeof(County),
    new PropertyMetadata(new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)), new PropertyChangedCallback(OnFillChanged)));

Step 3: Hook up a property changed callback and run the animation

Then, all you need to do is go into the property changed callback that you have created and assign your the new valie of the property to the keyframe value of the animation you want to run. Then run the animation.

private static void OnFillChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    MyControlType thisControl = d as MyControlType;
    if ((thisControl != null) && (thisControl._myStoryboard != null))
    {
        SolidColorBrush newBrushHolder = (SolidColorBrush)e.NewValue;

        thisCounty._myKeyFrame.Value = newBrushHolder.Color;
        thisCounty._myStoryboard.Begin();
    }
}

And now every time you change that value in the control, it will animate to the new value. Simple as that.

How To Create a PART in Your Silverlight Custom Control

There are about a dozen videos and tutorials on how to create a custom control in Silverlight 3. (Here’s my favorite, from Karen Corby. Skip to about 47 minutes for the tutorial part.)

But sometimes, you (and by “you”, I mean me) need help figuring out how to create a PART for a control because, let’s be honest, you don’t do it all the time and no one has a blog post on just this little part of control building.

If you’re wondering what a PART is, here’s a short explanation: A PART is a naming convention that allows a control (code) to make a contract with the control template (XAML) in Silverlight. The control says to the template, “I’m going to be doing something programmatic with this part, so it better be there”. The template responds, “Here’s that part you wanted.”

I not actually talking down to anyone, this is really how my brain works.

There are basically five steps in creating a PART. I think you can actually do it in less, but I’m trying to follow what I think is proper coding practice. In this tutorial, we’re going create parts out of a Button and also a Storyboard (partly because there are different ways to assign a PART if it is in located in the control resources like a Storyboard is).

Step 1: Define the control template parts you’ll need

Outside of the control class we need to add the TemplatePart attributes. Inside the class, we need to define the names of the UI objects we’re going to turn into parts as well as create some corresponding objects in the control so we can access those PARTs.

[TemplatePart(Name = MyControl.StoryboardString, Type = typeof(Storyboard))]
[TemplatePart(Name = MyControl.RootElementString, Type = typeof(FrameworkElement))]
[TemplatePart(Name = MyControl.ButtonString, Type = typeof(Button))]

public class MyControl : Control
{
    private const string StoryboardString = "PART_MyStoryboard";
    private const string RootElementString = "PART_RootElement"
    private const string ButtonString = "PART_MyButton";

    private Storyboard _targetStoryboard;
    private FrameworkElement _rootElement;
    private Button _targetButton;

What we’re going to do here is remarkably stupid because I don’t have the creativity right now to do something cool. When we press the button, we’ll play the storyboard. We need the RootElement because… you’ll see in a moment.

Step 2: Make sure you have a XAML template properly named to correspond with the part

We have three parts we’re getting here, so this is a stripped down template that just has the three PARTs named appropriately. If the names are not the same as the strings above, it will not work.

<StyleTargetType="local:MyControl">
    <
SetterProperty="Template">
        <
Setter.Value>
            <
ControlTemplate TargetType="local:MyControl">
                <
Grid x:Name="PART_RootElement">
                    <
Grid.Resources>
                        <
Storyboard x:Name="PART_MyStoryboard">
                          
<!– Whatever animations you want here –>
                      
</Storyboard>
                    </
Grid.Resources>
                    <
Button x:Name="PART_MyButton" />                       
                </
Grid>
            </
ControlTemplate>
        </
Setter.Value>
    </
Setter>
</
Style>

Step 3: Assign the XAML PART to the code PART in the OnApplyTemplate method

Now we just have to write a custom OnApplyTemplate method that will grab the XAML elements and assign them to objejcts within the control code. There are two key methods you’ll use. The first is GetTemplateChild, which will pull out any UI element in the XAML that is named and not in the resources.

If you want to get something in the resources, you need to refer to the UI element that holds those resources. This is why we needed the root element as a PART. So, enough of my blabbing… here’s the code:

public override void OnApplyTemplate()
{
    base.OnApplyTemplate();

    _rootElement = GetTemplateChild(MyControl.RootElementString) as FrameworkElement;
    //Make sure we actually got the template applied.
   
if (_rootElement != null)
    {
        _targetStoryboard = _rootElement.Resources[MyControl.StoryboardString] as Storyboard;
        _targetButton = GetTemplateChild(MyControl.ButtonString) as Button;

        _targetButton.Click +=new RoutedEventHandler(_targetButton_Click);       

    }
}

Now we have all the PARTs assigned so we can do something like adding an event handler to the Button so that, when it is clicked, it runs the storyboard.

void  _targetButton_Click(objectsender, RoutedEventArgs e)
{
     _targetStoryboard.Begin();
}

And that’s how you add a PART… both in the regular XAML template and in the resources of the template.

Building Custom Template-able WPF Controls

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