Naveen's Weblog

Bridge to future

Posts Tagged ‘Blend’

Customize a slider in WPF, Step by Step Tutorial

Posted by codingsense on February 1, 2010


Today let us explore how to customize a slider control in WPF. I have seen a lot of explanation and looked many articles on net about the slider, but i got the the better idea about it only when I implemented it in my own way.
Let me share the same step by step method with you all.

Download Source (7.8 Kb)

So lets begin, First create a WpfApplication in VS2008 and insert a slider control in the grid layout.Open the designer and click on the XAML view. You will see the below code.

<Slider Name="CusomSlider" Height="25" VerticalAlignment="Top" Margin="46,65,37,0" />····

Now we have to override the Style property of the slider to give it the look we want. We will name the style as MyCustomStyleForSlider and override the style method as below code,

<Slider Name="CusomSlider" Style="{StaticResource MyCustomStyleForSlider}" Height="25" VerticalAlignment="Top" Margin="46,65,37,0" />

Slider control is made up of many subcontrols, those include Track which inturn include Track.IncreaseRepeatButton, Track.DecreaseRepeatButton, Track.Thumb.
Thumb is the main sub control that makes the rectangle shape that moves left and right. The same thumb can also be found in horizontal and verticle scrollbars. So lets insert the following default template of all the controls that all together make the slider control.

<Style x:Key="MyCustomStyleForSlider" TargetType="{x:Type Slider}">
<Setter Property="Template">
<ControlTemplate TargetType="{x:Type Slider}">
<Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"><Grid>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto" MinHeight="{TemplateBinding MinHeight}"/>
<RowDefinition Height="Auto"/>
<TickBar x:Name="TopTick" Visibility="Collapsed" Fill="{TemplateBinding Foreground}" Placement="Top" Height="4" Grid.Row="0"/>
<TickBar x:Name="BottomTick" Visibility="Collapsed" Fill="{TemplateBinding Foreground}" Placement="Bottom" Height="4" Grid.Row="0"/>
<Border x:Name="TrackBackground"  
 BorderThickness="1" CornerRadius="1"
 Margin="5,0" VerticalAlignment="Center" Height="4.0" Grid.Row="1" >
<Canvas Margin="-6,-1">
<Rectangle Visibility="Hidden" x:Name="PART_SelectionRange" Height="4.0"
 Fill="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"
 Stroke="{DynamicResource {x:Static SystemColors.ControlDarkDarkBrushKey}}"
<Track x:Name="PART_Track" Grid.Row="1">
<RepeatButton Command="{x:Static Slider.DecreaseLarge}"/>
<RepeatButton Command="{x:Static Slider.IncreaseLarge}"/>
<Thumb x:Name="Thumb" Background="Black"/>                                        

Now run the application and check how it looks and works, click on its right and left and a small dot i.e Thumb without any style moves right and left.

Now lets apply style to the thumb and name it as CustomThumbForSlider, below is the implementation.

·<Style x:Key="CustomThumbForSlider" TargetType="{x:Type Thumb}">
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Template">
<ControlTemplate TargetType="{x:Type Thumb}">
<Ellipse Fill="#FF8F4040" Stroke="#FF000000" Height="15" Width="15"/>

and override the above style to the thumb.

<Thumb x:Name="Thumb" Style="{StaticResource CustomThumbForSlider}" Background="Black"/>

After overriding the Thumb style lets have a look of the slider control,

Great, i.e The important thing that makes the slider control is the IncreaseRepeatButton and DecreaseRepeatButton, when clicked on ends they decrease in the size to the amount of the Tickbar value making the other button grow in size and that gives us the illusion that the thumb is moving. Nice move right ok lets get furthur.

Now we need to hide the Increase and decrease repeat buttons so lets create their styles.

<Style x:Key="SliderRepeatButtonStyle" TargetType="{x:Type RepeatButton}">
<Setter Property="OverridesDefaultStyle" Value="true"/>
<Setter Property="IsTabStop" Value="false"/>
<Setter Property="Focusable" Value="false"/>
<Setter Property="Template">
<ControlTemplate TargetType="{x:Type RepeatButton}">
<Rectangle Fill="Transparent"/>

Ok apply the styles to the repeat buttons and run the application, you will see that we have only the thumb that moves left and right on clicking but we dont see any track. So now we shall give border control a proper background and brush so that we get a good look at the starting and ending of the slider control. Lets create a style for both of these properties and apply them to the border.

<SolidColorBrush x:Key="HorizontalSliderTrackNormalBackground" Color="#FFE7EAEA"/>
<LinearGradientBrush x:Key="HorizontalSliderTrackNormalBorder" EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="#FFAEB1AF" Offset="0.1"/>
<GradientStop Color="White" Offset=".9"/>
<Border x:Name="TrackBackground" 
 Background="{StaticResource HorizontalSliderTrackNormalBackground}"
 BorderBrush="{StaticResource HorizontalSliderTrackNormalBorder}"                                        
 BorderThickness="1" CornerRadius="1"
 Margin="5,0" VerticalAlignment="Center" Height="4.0" Grid.Row="1" >

Now run the application, you can see that we have customized the design of our slider control.

Change the ellipse control or the border styles to whatever you desire and you will be able to create your own design for the slider control.
Change some of the properties of tickbar, thumb and repeat buttons and see how they behave, which will give you more hands on with slider controller.


Happy Learning,
Codingsense 🙂

Posted in C#, WPF | Tagged: , , , | 17 Comments »

Data Triggers and Usage in XAML

Posted by codingsense on November 25, 2009


DataTrigger represents a trigger that applies property values or performs actions when the bound data meets a specified condition.

In this sample we will explore how this property can be utilized on how we need it to behave. In this sample I will concentrate on Style Triggers and apply them on the datagrid, in similar fashion it can be applied to any of the container control.

Till now I have been using Data Triggers in many of the places in my project. Combining all the solutions I have made a sample in which i will be describing all the types of usages of Data Triggers.

Let us imagine a collection of Fathers which hold FirstName of fathers. Each father has a kids collection where all his kids names are stored.
The collection are displayed in a datagrid and the rows are displayed using a Listview and a gridview.

<my:DataGrid AutoGenerateColumns="False" Margin="28,39,33,21" Name="dataGrid1">············
<ListView Name="Kids" ItemsSource="{Binding Kids}">························
<GridViewColumn  Header="Kids" DisplayMemberBinding="{Binding Name}"/>····························
<my:DataGridTextColumn Header="Father Name" Binding="{Binding FirstName}"/>············

Now lets create some scenarios in our project in the format the details are to be displayed
Scenario1: Make the families background red where there are no kids
Scenario 2: Hide the families where the name of the father is less than 8 chars
Scenario 3: Make the font bold where the fathers name is greater than 8 chars and there are 2 kids

Download Source Code – 423Kb

Make the families background red where there are no kids
Binding is very flexible in WPF you can easily bind to any of the properties available in the class. Like in this scenario we need to check if the kids count in the family is 0. For this we need to declare a style and bind our RowStyle of the grid to the defined style. Lets work on it.
Lets declare a style and name it as CheckKids and check for the kids.count condition for 0.

<Style x:Key="CheckKids" TargetType="{x:Type my:DataGridRow}">············
<DataTrigger Binding="{Binding Kids.Count}" Value="0">····················
<Setter Property="Background" Value="Red"/>················

In the collection Mr.Ramiayaa has no kids so background of his row is made red.

Hide the families where the name of the father is less than 8 chars
Now comes the challange how will you check fatherName < 8 in XAML. Pretty tricky right. Here is a simple method to be followed. What if we have another property in our class which returns true or false by checking the fathername.length. It will help us to acheive our goal.

Lets Declare a property in Father class and name it as IsLengthLessThanEight, which will return if the father name is less than 8 char or not. It will look like

public bool IsLengthLessThanEight
get { return (FirstName.Length < 8); }

By this we can be very sure that we can write our own properties and bind it to make anything possible.
Now lets declare the style and name it FatherNameLessEightChar and bind it to our declared property IsLengthLessThanEight
and check the desired condition.

<Style x:Key="FatherNameLessEightChar" TargetType="{x:Type my:DataGridRow}">············
<DataTrigger Binding="{Binding IsLengthLessThanEight}" Value="True">····················
<Setter Property="Visibility" Value="Hidden"/>················

In the collection we have only one father who has the name less than 8 that is Mr.Rocky that name is to be hidden.

Make the font bold where the fathers name is greater than 8 chars and there are 2 kids
Here comes the next challange how will we check more than one condition in XAML. Is it possible or should we declare another property and check 2 conditions in our class. For this we have MultiDataTrigger which will help us to check multiple conditions in XAML and set property accordingly. Cool.
Lets declare a style and name it CheckNameAndKidsCount and use the MultiDataTrigger.

<Style x:Key="CheckNameAndKidsCount" TargetType="{x:Type my:DataGridRow}">············
<Condition Binding="{Binding IsLengthLessThanEight}" Value="False"/>························
<Condition Binding="{Binding Kids.Count}" Value="2"/>····················
<Setter Property="FontWeight" Value="Bold"/>················

Here we check both the conditions i.e First we check if father name is greater than 8 char with the help of the IsLengthLessThanEight that we have defined and next condition we check if the kids count is 2 or not. If both the conditions are satisfied then the font of the family is made bold.
In our collection we have Mr.Balasubramanyam whose name is greater than 8 char and has 2 childrens so his row should be made bold.

Wow all the scenarios have completed and we have got the desired output for all of them. Thanks to DataTrigger for simplifying the life. In this similar fashion we can declare style trigger and data trigger to make various styles depending on the data that is bound.

References :

Cheers 🙂
Naveen Prabhu

Posted in WPF | Tagged: , , | 1 Comment »

Refresh UI elements on collection changed using ObservableCollection in WPF

Posted by codingsense on November 16, 2009


In windows application when we would bind a list with any UI control, on changing of the list we should have refreshed the UI element or reload the list into the UI element. Imagine how tiresome it was if the list was referenced in many UI elements.
In WPF if we are implementing the same structure then we can use INotifyPropertyChanged or INotifyCollectionChanged to minimize our work.
If we are working on a list then we can inherit the list from ObservableCollection which in turn implements the 2 interface mentioned above. By using ObservableCollection we can notify the controls that the list to which they are bound has been changed and ask them to refresh their selves. This will minimize the work to maximum extent and the same time can be utilized for better activities.

In this post let me demonstrate you on how ObservableCollection can be implemented and how the changes to list can automatically refresh the UI element.

Download Source Code (11 KB)

Let me brief on the key things
Bind Textbox to a property of another UI element (Listbox) that returns Object in SelectedItem:
The text box is bound to ListBox.SelectedItem but the selected item will return a object of type PersonName. That is to be split into FirstName and LastName and shown in txtFirstName and txtLastName respectively. Here you have a good option while binding the textbox and the engine will take care of the splitting you can just bind as follows
For txtFirstName I have used binding as

Text="{Binding Path=SelectedItem.FirstName, ElementName=MyListBox, Mode=TwoWay, UpdateSourceTrigger=Explicit}"

As you can see i have specified SelectedItem.FirstName and at runtime the selectedItem will change to the object that is focused. Similarly we can bind to txtLastName.


In UpdateSourceTrigger you have 3 options PropertyChanged, LostFocus, Explicity. I have used Explicity to handle our own customizations before updating the actual source and the customization can be handled in the save event.

NameList nameList = MyGrid.GetValue(Grid.DataContextProperty) as NameList;
PersonName currentPersonName = MyListBox.GetValue(ListBox.SelectedItemProperty) as PersonName;
PersonName NewPersonName = new PersonName(txtFirstName.Text, txtLastName.Text );
int IndexOfOriginal = nameList.IndexOf(currentPersonName);
nameList[IndexOfOriginal] = NewPersonName;

By just changing the List the newer values are reflected in the UI elements those are bound to the list.
For any clarifcation please feel free to comment.


Happy Learning 🙂

Posted in WPF | Tagged: , | 2 Comments »

Customized animating listbox WPF

Posted by codingsense on November 1, 2009

Hi All,
I had seen some of the 3rd party controls and was wondering what these people do in attaining good graphics in those controls. After carefully studying i got some tricks from which you can acheive the same styles.

Just have a look at this one, by just modifying some property i make the listbox to display items like a rack of books in a shelf .

Items of list box like Books in a Rack

And when you hover the mouse over it, the book will open and show you the details. Isnt it great

Books opens up when mouse hovers on it

Download source code – 210 Kb

Steps taken to acheive the above effects,

  • Databind a listbox using the xml file given in the project
  • Right click on the listbox and navigate to Edit other template -> Edit layout of items -> Edit a copy -> Enter any name you want to define -> click ok
  • In object and timeline in interaction window ( if not found click window menu -> interaction) click virtualizationStackPanel -> In properties( if not found click window menu -> properties) make orientation to horizontal from vertical
  • Click the return button in objects and timeline to return to the main page.
  • Select the listBox right click it and navigate to Edit Other Templates -> Edit generatated items -> Edit a copy
  • In the opened screen go to objects and timeline window (interaction window)
  • Select the stack panel and go to its properties, change the background that you want to apply to each item in the list box
  • Go to Transform group in properties and in RenderTransform
  • Select the rotate tab. Give an angle of -50
  • Select the skew tab and enter X value as -50, you will see the transform in each listbox item
  • Now just we need to remove the space between the items and its pretty much easier just give ve value in right margin. Eg: Give -30 in the right margin. This will bring all the items closer.

Now only we have to implement is Animation.First we shall create a story board

  • Click + on in the object and timeline to create a new story board, enter OnMouseIn and click ok
  • Select the stack panel
  • In timeline set the current time to 0.5 sec and Record a keyframe to indicate the initial state of our item.
  • Next we will tell the timeline what should happen after 0.5 sec. Move the timeline pointer to 1 Sec
  • And open the properties of stack panel and set the following values, -10 to right margin, 0 to angle and 0 to x in skew.
  • Run the timeline and see what happens and do any modification if it can enhance the animation.
  • Stop the timeline recording.

Next we need to define another storyboard that will move the list item back to the original position

  • So click Add new story board, Give it a name OnMouseOut and click ok
  • Take the current timeline to 1sec and insert a keyframe to indicate the final position of our animation.
  • Move the current pointer to 0.5 sec and set the properties, -30 as right margin, -50 as angle and -50 as x in skew.
  • Now since our animation is ready we just need to bind an event to invoke the story board, for that follow the setps.
  • In triggers click the +Event and select the target element Ismouseover event and set the value true.
  • In actions when activating select OnMouseIn begin
  • In actions when deactivating select on MouseOut begin
  • Run the application

Happy Learning 🙂
Naveen Prabhu


Posted in WPF | Tagged: , , | 2 Comments »

Basics of Reflection in WPF

Posted by codingsense on May 17, 2009

Reflection in WPF is a good feature to create better visual effects.

Create Visual Brush:
To create a basic reflection in Expression Blend we have to create a Visual Brush, to create one follow the steps.

  1. Open Expression blend
  2. Drop a image in the window
  3. Select the image and Select Tools-> Make Brush Resouce -> Make VisualBrush Resouce -> Click Ok

As you do this a Visual brush of your image will be created that you can apply for any objects.

Lets test it.
Now add a rectangle, Select it and go to properties window, in Burshes Select Fill -> Brush Resouce
You will find the visual brush that is created Select it, the rectangle will fill with the image.
Once we know the steps to create a visual brush we can proceed with the reflection

Once we have the rectangle filled with the visual brush resouce, we get a lot of options how to reflect the image.

I will show you one example to start with

Select the Rectangle
Select Properties -> Transform -> Scale
Set X as -1

You will see a reflected image horizontally, the same reflection you can attain by giving -1 in Y.

Try all the options in Transform Tab and you will come to know about a lot of techniques.


Here for first Image i have made half of the Rectangle Transparent, by modifying a bit in Brushes -> Opacity mask.
For the second I have added 3 rectangles which are reflecting in different angles by modifying scale in Transform Tab, and then making the image 3d and rotating it.

Download Project : 2 Mb

Happy Learning 🙂

Posted in WPF | Tagged: , | Leave a Comment »

Video Library WPF

Posted by codingsense on May 17, 2009


I was searching for some good tutorials that would help me to learn WPF basics and here i have found one good WPF video library tutorial.


I just went through the tutorial and found it very helpful and easier to understand. I created the same project and added some zooming effects in it.

Download Project – 2.7 Mb


The zooming effects that i have added is explained in my post Zooming in WPF.

Happy learning 🙂

Posted in WPF | Tagged: , | Leave a Comment »

Zooming In WPF

Posted by codingsense on May 17, 2009


Today we shall see how we can zoom an image on hovering a mouse over it.
I will guide you the steps in this sample to acheive zooming in Expression blend.

Download Project 780KB

First, create a new project -> In project window (Window menu -> Project) right click on the project -> Add existing item -> browse a image file and add it.
Click on the image and it will get placed in the window.

Create Project and Add Image

Create Project and Add Image

From here i will be showing many steps in a single image, i will be marking the parts where modification is required with a circle, and numbers have been given next to the ovals to follow them in order.
Next, in interaction window ( Window Menu -> Interaction)

  1. select the image
  2. Cilck “+” button in objects and timeline. Enter OnMouseEnter in Name(Key) TextBox and Click Ok.
  3. Move the timeline to 3 milliseconds
  4. In Property window, select Transform tab, in it select scale tab
  5. Set x to 1.5
  6. set y to 1.5


For better understanding, move the yellow timeline from 0 to 3 ms and check how the image scales.
So we have created a timeline for what has to happen when the mouse enters in the image area. Next we have to create one more timeline to zoom out the image when the mouse is moved out of the image area. Lets see how we can do it.

  1. select the image
  2. Cilck “+” button in objects and timeline. Enter OnMouseLeave in Name(Key) TextBox and Click Ok.
  3. In Property window, select Transform tab, in it select scale tab
  4. Set x to 1.5
  5. set y to 1.5
  6. Move the timeline to 3 milliseconds
  7. In Property window, select Transform tab, in it select scale tab
  8. Set x to 1
  9. set y to 1


Now we have timeline for mouse enter and mouse leave events, now we just need to bind this timelines to the actual events, here it goes

  1. Open the triggers window
  2. Click -trigger to remove the default event
  3. Click +Event and a new event is created
  4. Select image from the drop down (if image is not available select the image in object and timeline window)
  5. Select MouseEnter event from the dropdown
  6. Click +
  7. Select the timeline to attach the event ( OnMouseEnter)

By this we have attached the mouse enter event with our time line, now we need to attach the mouse leave event with the other timeline.

  1. Open the triggers window
  2. Click +Event and a new event is created
  3. Select image from the drop down (if image is not available select the image in object and timeline window)
  4. Select MouseLeave event from the dropdown
  5. Click +
  6. Select the timeline to attach the event ( OnMouseLeave)

Now save the project and run it. when mouse enters the image area the image zooms in and when mouse leaves the image zooms out.

Hope you got the steps right. For any queries feel free to post a comment.

Happy Learning 🙂

Posted in WPF | Tagged: , | Leave a Comment »