Posts tagged ‘Tutorial’

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.

Creating a Programmatic Path in Silverlight (or WPF)

Download Project Files for Creating a Programmatic Path in Silverlight or WPF

(Note: The project is in Silverlight, but if you copy and paste the code into a WPF project, it should work without any changes)

Have you ever wanted to create a Path programmatically or create a Path in code behind or dynamically build a Path or hand code a Path in Silverlight or WPF?

Yes, I just said the same thing 4 different ways, but I’m trying to cast a wide net for Google to catch. One of the biggest troubles I have when I’m trying to do something new is that I don’t always know the proper terminology, so I try to think of all the ways people might want to ask the question.

I’ve been playing around with a good number of information visualization concepts recently and one thing that I’ve found that I needed was the ability to create a path programmatically.

One way to do that is to tackle and fully grok the Path data code system. (Good guides to it are here and here.) This system is really cool, but (unless I’ve missed something) they cannot be animated.

I wanted to build a path based off a data set, but that means that I have to build it programmatically. I didn’t find a lot of useful stuff on how to do this, so I thought I’d throw some out there.

First, because I’m a XAML guy, I’m going to provide a simple XAML example of a Path that can be animated:

<Path x:Name="MyPath" Fill="#FFA30000" Stroke="Black" Width="100" Height="100">
    <
Path.Data>
        <
PathGeometry FillRule="EvenOdd">
            <
PathFigure IsClosed="True" StartPoint="0,0">
                <
LineSegment Point="0,100"/>
                <
LineSegment Point="100,100"/>
                <
LineSegment Point="100,0"/>
            </
PathFigure>
        </
PathGeometry>
    </
Path.Data>
</
Path>

This path is a simple square and looks like this:

clip_image001

Now, let’s assume you want to recreate this programmatically using a collection of points that represent X,Y coordinates. If you’re using an ObservableCollection of Points (like I am) you can use the following method to return an the appropriate path.

Path createPath(ObservableCollection<Point> rawData)
{

    Path FinalPath = new Path();
    PathGeometry FinalPathGeometry = new PathGeometry();
    PathFigure PrimaryFigure = new PathFigure();

    //if you want the path to be a shape, you want to close the PathFigure
    //   that makes up the Path. If you want it to simply by a line, set
    //   PrimaryFigure.IsClosed = false;
   
PrimaryFigure.IsClosed = true;
   
    PrimaryFigure.StartPoint = rawData[0];

    PathSegmentCollection LineSegmentCollection = new PathSegmentCollection();

    for (int i = 1; i < rawData.Count; i++)
    {
        LineSegment newSegment = new LineSegment();
        newSegment.Point = rawData[i];
        LineSegmentCollection.Add(newSegment);
    }

    PrimaryFigure.Segments = LineSegmentCollection;
    FinalPathGeometry.Figures.Add(PrimaryFigure);
    FinalPath.Data = FinalPathGeometry;

    return FinalPath;
}

Once you have the path in place, you can just add it to your layout and it should show up. If you’re still confused, you can download the project that I created this in and walk through the rest of it yourself.

WPF Multi-Point Tutorials, Part 1.5: WPF Visualization of Wii Data

Download WPF Wii Data Visualizer (App only, 355K)
Download WPF Wii Data Visualizer (Visual Studio 2008 Source, 676K)

Warning: The project will not run if your Wii controller isn’t connected to your computer.

Using the WPF Wii Data Visualizer (Video)

OK, now that we’ve gotten our Wii Controllers all hooked up to our computers, it’s time to take a look at the data we’re getting from it.

Over the weekend, I pieced together a little application that will help us visualize the incoming Wiimote data in a way that would help understand the raw data points a little better as well as help out as we head toward our ultimate goal of multi-point WPF application development. This is what I came up with.

WPFWiiDataVisualizer

Disclaimer: The source code at this point is a mess. While the interface is all done in XAML and is very WPF, the code-behind is a hacked together mish-mash. I will at some point go back and restructure the code-behind to take advantage of the INotifyPropertyChanged interface. When I do that, I’ll post on it and we’ll see another example of why WPF is so freaking cool.

Embedded ListView Columns (Columns Within Columns)

Please Read: Strangely, when you do a Google search for “wpf” and “listview”, this is one of the top links. This is odd because this particular post is kind of an advanced tutorial. If you’re looking for more general information on styling the wpf listview, check out this post. It is probably much closer to what you’re looking for.

This is a bit of an advanced tutorial. I’m putting it up because I just figured out how to do it and I want to share. You can also download the project files for this tutorial (in zip format… requires .Net 3.5).

Recently, I received from my user experience designers a wireframe that looked something like this:

EmbeddedWireframe

As you can see, there are embedded categories (categories within categories) here. I considered many solutions (hacks), but I found that a deeper understanding of the ListView and how it works would allow me to resolve this issue very simply (and without even touching the code behind). Continue reading ‘Embedded ListView Columns (Columns Within Columns)’ »