Posts tagged ‘Silverlight 3’

Create A Snapping Slider In Blend Using Behaviors (Silverlight 3 or WPF)

UPDATE: It turns out that in WPF, there is an easier way to snap the slider. For integers, simply check the “IsSnapToTickEnabled” and set your TickFrequency accordingly. Which means that this behavior is really only useful for Silverlight, which doesn’t have those properties.

Behaviors are easily the coolest thing that has ever happened to anything.

Perhaps I overstate my case somewhat. But they’re still pretty cool.

To me, a wonderful example is the ability to let designers/developers get some really cool functionality out of the Silverlight or WPF slider.

Now, one might normally think that there is a simple way to make your slider values to snap to an integer or to some incremental number (perhaps base 2 or base 10). Alas, one would be wrong. There have been a couple solutions to this problem (see here and here), but they usually involve creating a new slider subclass with the additional functionality if you really want the interaction to be reusable.

However, behaviors makes all this unnecessary. What is even better is that there is no code difference between WPF and Silverlight on this one. That’s right… this tutorial and the code that goes with it works exactly the same in Silverlight as it does in WPF.

SnappingSlider Behavior (SnappingSlider.cs) – Works for Silverlight and WPF

WPF SnappingSlider Behavior (All Project Files)

Silverlight SnappingSlider Behavior (All Project Files)

You can also download the behavior here (just the cs file) which would make me happy because it ups my street cred among the Silverlight homies (says the whitest man on earth).

If you want to learn how to create it yourself, let’s get started.

In your project in Blend, right-click on the project and go to “Add New Item…”

clip_image001[4]

Choose “Behavior” from the list and type in the name of the behavior you want to create

clip_image001[6]

This is where Blend is way cooler than Visual Studio… it gives you pretty much all the code and imports all the appropriate references for creating a behavior. So, first change the behavior associated object type to a Slider:

public class SnappingSlider : Behavior<Slider>

And go into the inside the OnAttached method, enter the following code:

AssociatedObject.ValueChanged +=new System.Windows.RoutedPropertyChangedEventHandler<double>(AssociatedObject_ValueChanged);

Hint to Code Newbies: If you get to the “+=” part and hit the Tab key twice it will add the necessary code.

Inside the AssociatedObject_ValueChanged method, I added the following code:

private voidAssociatedObject_ValueChanged(objectsender, System.Windows.RoutedPropertyChangedEventArgs<double> e)
{
  
//Let the slider be equal to the Maximum and Minimum values
  
if((e.NewValue != AssociatedObject.Maximum) && (e.NewValue != AssociatedObject.Minimum))
    {
      
//Using the Minimum value as a starting point, only allow values that are
        //   a multiple of the SmallChange value. If you want to simply round to
        //   integers, set it so that:
        //   SmallChange = 1
      
doublecalcValue = Math.Floor((e.NewValue – AssociatedObject.Minimum) / AssociatedObject.SmallChange);
        calcValue = (calcValue * AssociatedObject.SmallChange) + AssociatedObject.Minimum;
        AssociatedObject.Value = Math.Round(calcValue);
    }
   
else
   
{
       
//Sometimes it hiccups on me, so I used this to catch those
       
AssociatedObject.Value = Math.Round(e.NewValue);
    }
}

Once you have that code in place, build the project (menu option Project –> Build Project).

Now you should have the behavior available in the “Assets” tab under “Behaviors” (at the bottom of the picture below).

clip_image001[8]

 

Just drag it onto your Slider and set the Minimum, Maximum and SmallChange properties appropriately. Remember that SmallChange is the value is that is acting as your increment controller.

How To Create A ListBox with CheckBoxes (or RadioButtons) In Silverlight 3

To set the scene: You have a ListBox that is being populated by some collection and you want the user to scroll through the ListBox and either check a bunch of things or check one thing. Basically, you want a list of checkable items. If this is what you’re trying to do, this is the tutorial that lets you do it without any code… simply by applying a style to your ListBox.

Download finished tutorial: ListBox With CheckBoxes (or RadioButtons) Project in Silverlight 3

Go here to see the final result.

First, you should know right off the bat that this tutorial is for Silverlight 3 only. It uses a data binding functionality called RelativeSource binding that isn’t available in earlier versions of Silverlight.

OK… to start out, right click on your ListBox and go to:

Edit Additional Templates –> Edit Generated Item Container (ItemContainerStyle) –> Edit a Copy…

clip_image001

Name your new template and Blend will generate the default ItemContainerStyle for the ListBox.

Split up the grid so that there is room for your CheckBox or RadioButton. I’m going to put mine on the left, set HorizonalAlignment and VerticalAlignment to “Center”, reset the Content property" and make the whole thing twice as big by setting the RenderTransform X and Y to 2.

clip_image001[5]

If you’re really picky about making sure that your CheckBox is centered appropriately, change the Width and Height to “16”.

OK… so we’ve got the CheckBox in there, but it doesn’t really do anything. So let’s set the binding so that it works. Sadly, Blend doesn’t have an obvious way (that I can see) of setting a RelativeSource binding, so just type this into your CheckBox (or RadioButton):

IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsSelected, Mode=TwoWay}"

This binding will make it so that when the user selects or unselects an item, the CheckBox or RadioButton will reflect this decision. Similarly, when the user checks or unchecks the CheckBoxes or RadioButtons, the selection will reflect these actions.

Now, we just need to make sure our selection option on the ListBox reflects our interface choice. If you’re using CheckBoxes, make sure that your ListBox SelectionMode is set to “Multiple” or “Extended”.

clip_image001[1]

If you’re using RadioButtons, it needs to be set to “Single”.

And you’re done! You can now set any ListBox to hold a list of checkable items simply by assigning it this ItemContainerStyle.

CheckBoxRadioButtonExample

And you should have something that looks and acts like this.

How To Get a Silverlight 3 AutoCompleteBox To Show Sample Data in Blend 3

Download Project Files for AutoCompleteBox Sample Data Project

So you’re playing around with Silverlight in Blend 3 and you set up some sample data. (If you don’t know how to do that, I’ll get to that in this tutorial too.) Your sample data is all set up and you’ve attached it to your AutoComplete box… but nothing happens. You get angry and throw your computer out a window (unless it’s a MacBook, in which case you apologize to it for flirting with Microsoft technologies and take it for a little cuddle), but you eventually think you want to try again and so you go looking for the problem on the internet. Hopefully that is what brought you here.

I talk too much, I know.

Just to start out at the beginning, if you didn’t know that Silverlight 3 had an AutoCompleteBox, that’s because it isn’t a default control. You can install it and several other fantastic controls via the Silverlight Toolkit. If you don’t have this installed, do so now.

With the Silverlight Toolkit installed, let’s just make sure we have the right problem.

OK… lets create our sample data. In the top right corner of Blend, you’ll see a couple of tabs. Click on the “Data” tab and click on the “Add sample data” menu and choose “Define New Sample Data…”

clip_image001

Name your database something short (you’ll see why later) and rename the “Collection” collection to something less confusing, like “Sample”. Add some string properties and give them handy names. You can see my sample data as a starting point…

clip_image001[5]

That’ll do for now. Now, draw an AutoCompleteBox into your UserControl and drag the Sample collection on top of it. It will set itself to be the default ItemsSource. Now, hit F5 to run your application. It should act like this one below… if you type stuff, nothing comes up… but if you type “e”, you can see (in my sample, at least), it shows a set of items labeled, “Expression.Blend.SampleData.AutoData.SampleItem”.

clip_image001[1]

This is because the filter being used by default in the AutoCompleteBox takes the items and converts them directly to strings. If the item itself is an object (like this example and like most real data you’re probably using), it will convert it into the string representation of that data type.

So let’s fix it. First, we’re going to create an ItemTemplate for our AutoCompleteBox so that we can actually see the data in it. The quickest way to do this is actually kind of silly. Create a ListBox in your app and drag the data collection into it. It will auto-generate a super simple ItemTemplate. Then right-click on your AutoCompleteBox and go to “Edit Additional Templates –> Edit ItemTemplate –> Apply Resource –> [name of generated template here]”

clip_image001[7]

Delete your ListBox, just to clean things up.

Now you’ll have an AutoCompleteBox that shows the data like you want it, but it’s still looking at the “Expression.Blend.SampleData.SampleItem” when you type in the box, so it’s not acting the way we want. In order to do that, we just have to override the “ToString()” method in the AutoData. Open up “AutoData.xaml.cs”

clip_image001[1]

Scroll down to the “SampleItem” class and make the beginning of that class look like this:

public class SampleItem : System.ComponentModel.INotifyPropertyChanged
{
    public override string ToString()
    {
        return Name;
    }

If you want to use another property as your text return, just use that property name instead of Name. If you want to use a combination of properties, you could do something like this:

return Name + " - " + CompanyName;

Although, if you want it to look at two fields, you should change the FilterMode to “Contains”

clip_image001[3]

And… tada! You’re done… unless you want to give it some styling to better enhance the user experience (like putting the name at the top so that it draws the eye).

clip_image001[3]

Also valuable, check out Tim Heuer’s post on turning the AutoCompleteBox into an editable ComboBox.

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.