Archive for the ‘Combobox’ Category.

How To Wrap Text in a Silverlight 3 ComboBox

Download ComboBox TextWrapping Tutorial Project

Sometimes you just want stuff to work the way you want it to work. I want a property on the Silverlight ComboBox that says “WrapText”. But alas there is not one, so I have to do it myself.

So your ComboBox looks like this:

and you want it to look like this:

clip_image001[13]

Let’s make that happen.

First, we need to make sure that the DataTemplate is going to act in such a way that it is compatible to having the data inside it wrap.

So… right-click on your ComboBox and go to: “Edit Additional Templates –> Edit Generated Items (Item Template) –> Edit Current”

clip_image001[5]

If that option isn’t available, go to “Create Empty” The DataTemplate in my sample looks like this:

clip_image001[7]

Hopefully, you have the binding information available for your data. If not, check out this post on creating sample data for the purpose of styling things. Make sure all the Widths and Heights (but especially the Widths) are set to “Auto”.

clip_image001[9]

And make sure your TextBox or TextBlock has TextWrapping=”Wrap”

clip_image001[11]

So now your ComboBox wraps in the main section… which is awesome, but you still have this happen when you open up the DropDown (PopUp)

clip_image001[15]

If you want that to wrap as well, the solution isn’t hard so we’ll deal with it here instead of giving it another post.

First,change the HorizontalContentAlignment on the ComboBox to be “Stretch”.

clip_image001[17]

Next, right click on the ComboBox and go to “Edit Additional Templates –> Edit Generated Item Container (ItemContainerStyle) –> Edit a Copy…”

clip_image001[19]

What is happening is that the ItemContainerStyle element is requesting all the space in the world from it’s parent and since the parent with the ultimate authority is a PopUp, it sees no reason to constrict the ItemContainerStyle with irritating constraints, so the text element finds no reason to start wrapping. So, we’re going to tell the ItemContainerStyle that it can only request a certain amount of space. In this particular case, we’re going to set MaxWidth=”200”

clip_image001[21]

And we get this:

finalcomboboxwrapping

And we’re happy.

Or at least I hope we’re happy. If you’re not happy, mention your problem in the comments and I’ll try to get back to you with any tweaks or updates you need.

Styling A ComboBox In Silverlight 3

Download ComboBox Styling Project Files

This post is meant to be a center point for topics related to styling the Silverlight 3 ComboBox. It will go over the basic about ComboBox styling and will also get updated with links to tutorials about common design problems with the ComboBox.

So, let’s get started…

If you want to change the look of the main ComboBox or the ComboBox drop down (popup),

clip_image001[6]

clip_image001[4]

you’re going to want to change the main template of the ComboBox.

As an aside, in order to make this as simple as possible, we’re not going to connect out ComboBox to any data… we’re just going to add a bunch of ComboBoxItems to it. To do this, click on the double-arrow at the bottom of the toolbar and type “combo” into the search field.

clip_image001[10]

Click on the ComboBoxItem and draw it into the ComboBox a couple times. This will give your items some weird heights and widths, so change those if that bothers you. We now have enough items to be able to see the drop down for the purposes of styling it.

OK… let’s get started with actually working on the ComboBox template. Right click on the ComboBox and going to “Edit Template –> Edit a Copy…”

clip_image001[8]

This will dump a copy of the default ComboBox style and template into your resources that you can play around with.

Let’s say we want to do something as simple as changing the corners in the main comboBox and the drop down to make them a little more rounded.

When we look at the template, we should see something that looks like this:

clip_image001[12]

Let’s start with rounding the corners of the pop-up, since we can do that from right here. On the PopupBorder element, let’s change the CornerRadius to “0,0,16,16”. And let’s change the border color and thickness just cause we wanna. We end up with something like this:

clip_image001[16]

Now, lets work on changing the corners on the rest of the ComboBox. As it turns out, most of the visual elements in the ComboBox are in the DropDownToggle ToggleButton and go to ControlTemplate by right clicking on it and going to “Edit Template –> Edit Current”

clip_image001[18]

Now, we can see 8 rectangles that make up the design of the ComboBox. If you wanted to simplify the design, you could get rid of them and put something else in, but we’re going to assume for the moment that you just want to change the corners. Go through the rectangles and if RadiusX and RadiusY are 3, change them to 16 an if they are 2, change them to 15.

clip_image001[20]  becomes clip_image001[22]

And you have something that is… not that attractive, but it is definitely different.

How To Use a ListView or DataGrid In a ComboBox Drop Down (Without A Line Of Code)

Super cool new thing I learned today. In WPF, we can make it so that the drop down (popup) on a ComboBox displays the data in a ListView. Because of the fact that I believe the DataGrid will eventually overtake the ListView as the gold standard for data display in WPF, we’ll do it both ways.

This tutorial is done entirely in Blend and without a line of code.

Step 0) (for the DataGrid only)

Go to Code Plex and download the WPF Toolkit. Extract to a convenient location.

Right-Click on the References folder in your project tab and click “Add Reference…”

clip_image001

Navigate to the location you extracted the WPFToolkit.dll file, select it and hit OK.
clip_image001[6]

Step 1) Select the ComboBox you wish to change and edit the ControlTemplate by right-clicking and selecting “Edit Control Parts (Template) –> Edit a Copy…”

clip_image001[1]

Step 2) Find the ItemsPresenter. This is what would normally display our ItemsSource.

clip_image001[3]

We’re going to get rid of it. And the ScrollViewer for good measure.

Step 3) Where the ScrollViewer is, put in a ListView or a DataGrid, whichever one you’re using.

clip_image001[5]

Now, go the properties of that ListView or DataGrid and click on the box to the right of “ItemsSource”

clip_image001[11]

and, in the resulting menu, select “Template Binding –> ItemsSource”.

clip_image001[7]

Set the DataContext of the ListView or DataGrid to the DataContext of the parent ComboBox using the same process.

And… you’re done! Open the ComboBox and you will see that you can select items in the ListView or DataGrid in the ComboBox dropdown and see those items change the selection of the ComboBox.

clip_image001[13]

You’ll notice that this is probably not yet an ideal solution. For example, when we select an item, the dropdown doesn’t automatically close. Your best bet is to use the SelectionChanged event to trigger some logic to close the ComboBox dropdown.

Building a Silverlight ComboBox Using Attached Behaviors

I recently needed to use a ComboBox in an application I was writing.  Because there is no built-in ComboBox in Silverlight I decided to explore building one using attached behaviors.  If you’re not familiar with this design pattern, check out Nikhil’s posts.  My ComboBox behavior is loosely based on his AutoComplete behavior.  I also make use of Julian’s ButtonCommands class, which he describes in this post.

Silverlight ComboBox Project Test Page - Mozilla Firefox

I started with a simple behavior interface:

/// <summary>
/// Represents a contract for encapsulation of logic that can be added
/// to a dependency object through a pattern of attachment.
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IBehavior<T> where T : DependencyObject
{
    /// <summary>
    /// Gets the associated object.
    /// </summary>
    /// <value>The associated object.</value>
    T AssociatedObject { get; }

    /// <summary>
    /// Attaches to the specified associated object.
    /// </summary>
    /// <param name="associatedObject">The associated object.</param>
    void Attach(T associatedObject);

    /// <summary>
    /// Detaches from the associated object.
    /// </summary>
    void Detach();
}

Which I used to implement a ComboBoxBehavior class.  I chose to use FrameworkElement because I wanted to be able to attach this ComboBox to different controls.  Possibly a TextBlock, a TextBox, a Border … any number of controls.  We’ll come back to this later …

public class ComboBoxBehavior : IBehavior<FrameworkElement>
{
    ...
}

After creating the behavior I created a simple static class which had a single attached property of type ComboBoxBehavior.

public static class Behaviors
{
    public static readonly DependencyProperty ComboBoxProperty =
        DependencyProperty.RegisterAttached(
            "ComboBox",
            typeof(ComboBoxBehavior),
            typeof(Behaviors),
            new PropertyMetadata(
                new PropertyChangedCallback(OnComboBoxChanged)
            )
        );
    ...
}

Attach() and Detach() are called in the property changed callback.

private static void OnComboBoxChanged(
    FrameworkElement element,
    ComboBoxBehavior oldValue,
    ComboBoxBehavior newValue)
{
    if (oldValue != null)
    {
        oldValue.Detach();
    }

    if (newValue != null)
    {
        newValue.Attach(element);
    }
}

You can then wire up the behavior in XAML … I’m using a Border control in this example.

<Border
    xmlns:local="clr-namespace:SilverlightComboBox">
    <local:Behaviors.ComboBox>
        <local:ComboBoxBehavior
            Opened="SimpleComboBoxBehavior_Opened"
            ItemSelected="SimpleComboBoxBehavior_ItemSelected"
            ShowComboBoxCommand="{StaticResource ShowComboBoxSimple}">
        </local:ComboBoxBehavior>
    </local:Behaviors.ComboBox>
    <TextBlock
        x:Name="uxSimpleComboBox"
        Margin="4,0,4,0">
    </TextBlock>
</Border>

So onto the workhorse … the behavior itself.  The way I built this behavior to work is it fires an event, Opened,  when the DropDown is opened, in which you can set the ItemsSource and the SelectedIndex of the ItemsSource, as demonstrated in the following code:

private void SimpleComboBoxBehavior_Opened(
    object sender, ComboBoxOpenedEventArgs e)
{
    List<string> strings = new List<string>();
    strings.Add("A");
    strings.Add("B");
    strings.Add("C");
    strings.Add("D");

    e.ItemsSource = strings;

    var index = strings.IndexOf(uxSimpleComboBox.Text);
    e.SelectedIndex = index;
}

Once the user selects a value another event is fired, ItemSelected, which can also be handled:

private void SimpleComboBoxBehavior_ItemSelected(
    object sender, ComboBoxItemSelectedEventArgs e)
{
    if (e.SelectedItem != null)
    {
        uxSimpleComboBox.Text = e.SelectedItem.ToString();
    }
}

You may be wondering why I took this approach.  I decided to go down the eventing route because as I mentioned previously, I wanted to be able to attach this behavior to lots of different controls.  As such I felt that it should be up to the implementer to display the data as needed.

I also decided to use commands to drive the opening and closing of the DropDown.  This allows the user to declaratively specify when the DropDown is opened or closed.  If you look at the XAML for the behavior I’m wiring up a ShowComboBoxSimple command to the ShowComboBoxCommand.

ShowComboBoxCommand="{StaticResource ShowComboBoxSimple}"

This is an ICommand of type MultiDelegateCommand.  MultiDelegateCommand is a command which can register multiple delegates to call when it is executed.

I registered a MultiDelegateCommand instance in the Application Resources to be able to use it in the markup:

public Page()
{
    Application.Current.Resources.Add(
        "ShowComboBoxSimple",
        new MultiDelegateCommand()
    );

    ...

    InitializeComponent();

    ...
}

Lastly, I wanted to show the DropDown anytime any portion of the control I’m attaching to is clicked.  This is accomplished by subscribing to the MouseLeftButtonUp event when the associated object is being attached:

/// <summary>
/// Attaches to the specified associated object.
/// </summary>
/// <param name="associatedObject">The associated object.</param>
public void Attach(FrameworkElement associatedObject)
{
    AssociatedObject = associatedObject;
    AssociatedObject.MouseLeftButtonUp += AssociatedObject_MouseLeftButtonUp;
    AssociatedObject.LostFocus += AssociatedObject_LostFocus;
}
private void AssociatedObject_MouseLeftButtonUp(
    object sender, MouseButtonEventArgs e)
{
    if (ShowComboBoxCommand != null && !IsDropDownOpen)
    {
        ShowComboBoxCommand.Execute();
    }
}

And that’s basically it!  You may be wondering … does this control support complex types?  You betcha! The source show’s a sample of working with complex types.  Here is shown a complex City type with a Name property.

<DataTemplate x:Key="CityTemplate">
    <TextBlock
        Text="{Binding Name}"
        ToolTipService.ToolTip="{Binding Name}"/>
</DataTemplate>

...

<local:Behaviors.ComboBox>
    <local:ComboBoxBehavior
        Opened="ComplexComboBoxBehavior_Opened"
        ItemSelected="ComplexComboBoxBehavior_ItemSelected"
        ShowComboBoxCommand="{StaticResource ShowComboBoxComplex}">
        <local:ComboBoxBehavior.DropDownTemplate>
            <DataTemplate>
                <ListBox ItemTemplate="{StaticResource CityTemplate}" />
            </DataTemplate>
        </local:ComboBoxBehavior.DropDownTemplate>
    </local:ComboBoxBehavior>
</local:Behaviors.ComboBox>

Download: SilverlightComboBox.zip

Hope that helps!

Joe

Styling the ComboBox Dropdown (popup)

 This tutorial derives from the general “How to Style the ComboBox” set of tutorials.

First let’s make sure you’re in the right place. In this tutorial, we’re going to style the comboBox drop down (also known as the ComboBox popup) seen highlighted in red below.

CB_Image_1

We will not be styling the items inside the dropdown (highlighted in blue). You can learn how to do that here.

So… let’s just go after some of the basics in styling the dropdown. We’ll give it a new background, a new border and we’ll round the edges to make it just a little more bubbly.

To start out, we’ll need to get to our comboBox control template, so right click on the comboBox in the Objects and Timeline window and go to “Edit Control Parts (Template) -> Edit a Copy…

CB_Image_2

Name it something you like and we’re on our way. 

We’ll be editing the PART_Popup. Whatever you do, don’t change the name to this sucker. Whenever you see a “PART_Something”, it is a necessary part of that specific control (hence the naming convention).

The ComboBox dropdown (which we’ll be calling a popup for the remainder of this post)  is made up of a low cost drop shadow (see more on that here), a border, a scrollviewer and the itemsPresenter.

CB_Image_3

Most of the standard styling we might want to do is probably going to happen in the Border titled DropDownBorder. We can alter the background and the border brushes easily enough by just changing them in the Properties window. But you may notice some quirky behavior from our scrollviewer when we change the CornerRadius. Below, I’ve changed the CornerRadius to “0,0,10,10” and we can see that we lose part of the corner under the scrollviewer.

CB_Image_4

CB_Image_5

We can solve this easily enough by adding some padding through the Border. Below I’ve added a padding of “0,0,2,6“.

CB_Image_6

Better, but not really ideal. In a perfect world, we would be able to say that the border us able to cut off its content in that nice pretty rounded manner.  (If anyone knows how to do that… let me know, I haven’t given it hours of thought yet, but I’d love to know). In this case, however, this sub-optimization is the price we’re going to have to pay if we don’t want to have to go in and mess with the scrollbar style and template.

How Do I Style The ComboBox Items?

This is actually a continuation of my post on getting the ComboBox items to accept text wrapping, so I’ll be working from that point forward. If you’re coming fresh into this, you won’t be missing anything… but that is my explaination for the pictures containing wrapping text.

When last we left our heroes, we has a couple problems. The first was that our items were either black text on a white background and ran together in a very un-designer-y way.

BeginningViewComboStyling

The second was that the selected item background makes your eyes bleed such a horrid blue color you’ll feel like Paul Atreides staring at a stone burner.

Was that a little too geek? My apologies.

Continue reading ‘How Do I Style The ComboBox Items?’ »

The WPF Designers Guide to Styling The ComboBox

 The ComboBox is not the most complex of the WPF applications, but it can be a little tricky, so lets do a general overview post of it before we go into the specifics of how we’re going to make it work.

First of all, if you’re going to test your comboBox design, you should have it hooked up to an ItemsSource. Don’t have one? I have a tutorial in which I walk through attaching an RSS feed to your control. It was originally written for the ListView, but it will work fine for a ComboBox.

To start out… this is your standard ComboBox:

unalteredComboBox

When working on a comboBox, you have a couple of options for the Items inside the ComboBox. If the options never change and are not data-driven, you can just toss come ComboBoxItems into it. Otherwise, you can connect it to some kind of ItemsSource (see the link above).

All of my examples are done with a data-driven ComboBoxes, but you should get the desired results if you run through the tutorials with ComboBoxItems.

First, a little bit about the structure of the comboBox.

Continue reading ‘The WPF Designers Guide to Styling The ComboBox’ »

How Do I Wrap Text (or Add TextEllipsis) In The ComboBox?

I’ve been spending the past several days fighting with the ComboBox in an attempt to make it so something very simple: Wrap text inside the combo box. I’ve finally figured it out, so I thought I’d share.

OK, first of all, make sure that your ComboBox is hooked up to something, even if that something is some random RSS feed. I have a post that can help you with that over here. Bind your comboBox to the “Items” part of the New York Times RSS feed.

You need to do this because, if you do not, you will have to set the same data template to every single ComboBoxItem that you add to the ComboBox. And that’s just no fun.

Starting out, your ComboBox should look something like this:

ComboBoxDefault

Right click on your ComboBox and select “Edit Other Templates -> Edit Generated Items (ItemTemplate)-> Create Empty…” Give your new data template a name and Blend will take you into the Data Template design.

Continue reading ‘How Do I Wrap Text (or Add TextEllipsis) In The ComboBox?’ »