Naveen's Weblog

Bridge to future

Posts Tagged ‘WPF’

Grouped RadioButton for WPF Datagrid

Posted by codingsense on February 9, 2010

Hi,

One of my friend was having a problem in implementing the radio button in datagrid, if implemented he wanted to know how to group them so that in 2 different columns radio button will be grouped as one. So after few attempts I found the following method and explained him the implementation.

To implement a radio button you have to use the DataGridTemplateColumn, where you can create your custom column for datagrid.

Download Code(5.7Kb)

The radio button was quite easily implemented as the following code




<dg:DataGridTemplateColumn
					Header="Male">                    
<dg:DataGridTemplateColumn.CellTemplate>                        
<DataTemplate>                            
<RadioButton IsChecked="{Binding Male}" />                        
</DataTemplate>                    
</dg:DataGridTemplateColumn.CellTemplate>                
</dg:DataGridTemplateColumn>                
<dg:DataGridTemplateColumn
					Header="Female">                    
<dg:DataGridTemplateColumn.CellTemplate>                        
<DataTemplate>                            
<RadioButton IsChecked="{Binding Female}" />                        
</DataTemplate>                    
</dg:DataGridTemplateColumn.CellTemplate>                
</dg:DataGridTemplateColumn>





After the implementation of the radio button we faced a challenge to group it up and we came with a very beautiful idea of giving a group name to both of them and here is what we did, we gave a groupname as “RadioGroup” to both of the radio button as




<dg:DataGridTemplateColumn
					Header="Male">                    
<dg:DataGridTemplateColumn.CellTemplate>                        
<DataTemplate>                            
<RadioButton GroupName="RadioGroup" IsChecked="{Binding Male}" />                        
</DataTemplate>                    
</dg:DataGridTemplateColumn.CellTemplate>                
</dg:DataGridTemplateColumn>                
<dg:DataGridTemplateColumn
					Header="Female">                    
<dg:DataGridTemplateColumn.CellTemplate>                        
<DataTemplate>                            
<RadioButton GroupName="RadioGroup" IsChecked="{Binding Female}" />                        
</DataTemplate>                    
</dg:DataGridTemplateColumn.CellTemplate>





Oops we were again into a problem, now all the cells were grouped together so we could select only one out of whole group.
Think Think Think is what we did, then we got a idea to have a group name that is unique for each row that is created. So we created a property called index which will be unique across each person, and we binded our column with the index, so that for each person instance the index will be same but not for 2 persons in the collection.
And this gave us the final solution of grouped radio button. Here is what we did.




 <dg:DataGridTemplateColumn
					Header="Male">                    
<dg:DataGridTemplateColumn.CellTemplate>                        
<DataTemplate>                            
<RadioButton GroupName="{Binding Index}" IsChecked="{Binding Male}" />                        
</DataTemplate>                    
</dg:DataGridTemplateColumn.CellTemplate>                
</dg:DataGridTemplateColumn>                
<dg:DataGridTemplateColumn
					Header="Female">                    
<dg:DataGridTemplateColumn.CellTemplate>                        
<DataTemplate>                            
<RadioButton GroupName="{Binding Index}" IsChecked="{Binding Female}" />                        
</DataTemplate>                    
</dg:DataGridTemplateColumn.CellTemplate>                
</dg:DataGridTemplateColumn>




So the main thing that has to be noted is, we should have a property that will remain unique accross the collection. If we have such property just bind it with the groupname and radio button will work absolutely fine.

Hope you found it useful. For any clarification or any better suggestions please revert back.

Happy Learning,
Codingsense :)

Posted in WPF | Tagged: , | 6 Comments »

Customize a slider in WPF, Step by Step Tutorial

Posted by codingsense on February 1, 2010

Hi,

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.

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


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">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Slider}">
<Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"><Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto" MinHeight="{TemplateBinding MinHeight}"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<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}}"
 StrokeThickness="1.0"/>
</Canvas>
</Border>
<Track x:Name="PART_Track" Grid.Row="1">
<Track.DecreaseRepeatButton>
<RepeatButton Command="{x:Static Slider.DecreaseLarge}"/>
</Track.DecreaseRepeatButton>
<Track.IncreaseRepeatButton>
<RepeatButton Command="{x:Static Slider.IncreaseLarge}"/>
</Track.IncreaseRepeatButton>
<Track.Thumb>
<Thumb x:Name="Thumb" Background="Black"/>                                        
</Track.Thumb>
</Track>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>


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">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Thumb}">
<Ellipse Fill="#FF8F4040" Stroke="#FF000000" Height="15" Width="15"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>


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">
<Setter.Value>
<ControlTemplate TargetType="{x:Type RepeatButton}">
<Rectangle Fill="Transparent"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>


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"/>
</LinearGradientBrush>
<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.

References:
http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.thumb.aspx
http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.tickbar.aspx

Happy Learning,
Codingsense :)

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

Data Triggers and Usage in XAML

Posted by codingsense on November 25, 2009

Hi,

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">············
<my:DataGrid.RowDetailsTemplate>················
<DataTemplate>····················
<ListView Name="Kids" ItemsSource="{Binding Kids}">························
<ListView.View>····························
<GridView>································
<GridViewColumn  Header="Kids" DisplayMemberBinding="{Binding Name}"/>····························
</GridView>························
</ListView.View>····················
</ListView>················
</DataTemplate>············
</my:DataGrid.RowDetailsTemplate>············
<my:DataGrid.Columns>················
<my:DataGridTextColumn Header="Father Name" Binding="{Binding FirstName}"/>············
</my:DataGrid.Columns>········
</my:DataGrid>

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}">············
<Style.Triggers>················
<DataTrigger Binding="{Binding Kids.Count}" Value="0">····················
<Setter Property="Background" Value="Red"/>················
</DataTrigger>············
</Style.Triggers>········
</Style>

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}">············
<Style.Triggers>················
<DataTrigger Binding="{Binding IsLengthLessThanEight}" Value="True">····················
<Setter Property="Visibility" Value="Hidden"/>················
</DataTrigger>············
</Style.Triggers>········
</Style>

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}">············
<Style.Triggers>················
<MultiDataTrigger>····················
<MultiDataTrigger.Conditions>························
<Condition Binding="{Binding IsLengthLessThanEight}" Value="False"/>························
<Condition Binding="{Binding Kids.Count}" Value="2"/>····················
</MultiDataTrigger.Conditions>····················
<Setter Property="FontWeight" Value="Bold"/>················
</MultiDataTrigger>············
</Style.Triggers>········
</Style>


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 :
http://msdn.microsoft.com/en-us/library/system.windows.datatrigger.aspx

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

Hi,

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.


UpdateSourceTrigger:

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.

References: http://msdn.microsoft.com/en-us/library/ms668604.aspx

Happy Learning :)
Codingsense

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 »

N-Tier basic 3D WPF Application

Posted by codingsense on October 20, 2009


Hi All,

WPF (Windows Presentation Foundation) has given us a hand to move in 3D world. Great graphics and GUI can be attained using WPF. I have worked on several graphical projects in WPF, but was wondering whether the performance and ease will remain the same when building a big application, so was working on the same and until now i have found it very easy in deploying any kind of application. So i planned to expose my application to all of you so that you can use it any way, here is the project. This is just a basic sample and I am sure you will find more ways after exploring this application.

Contact Management

Version : 1.0.0.0
Date : 20/Oct/2009

Download Source Code and database – 344 Kb
Download Application and database – 341 Kb

Prerequisites:

  • .Net Framework 3 or above.
  • SQL server 2005 or above
  • better the system configuration better the graphics
  • To view source files you will need VS 2008 SP1 and for better understanding design, 3D and animations you will need Expression blend 2 or higher

In the Contact Management i have tried to explore many concepts in which we can acheive good graphical interfaces and flexible data binding.

Let me show you some of the snapshots of the application.

Login Screen

Login Screen with Pattern using Drawing brushes

Login Screen with Pattern using Drawing brushes

Main screen

Customized listbox to show data in horizontal view with good looking mouse hover to move scroll bar and 3D rotation.

Customized listbox to show data in horizontal view with good looking mouse hover to move scroll bar and 3D rotation.

Add New contact

Add new contact to your list

Add new contact to your list

Transparent About Screen with animating text

Transparent about screen with animating text

Transparent about screen with animating text

Here are some of the key features explored. In coming posts we will explore each one of the features and do’s and dont’s of them.

  1. Customizing a control
  2. Data binding from various datasources
  3. Animating a control with Event Trigger and Propery Trigger
  4. Creating 3D graphichs and brief on Viewport 3D
  5. Creating resources and using them in whole application
  6. Creating Themes or Skins and change whole interface depending on the selection
  7. IValueConverter – bringing data from many child table depending on the parent data selection.
  8. Path – change shapes of any control or window
  9. Transoform propery

If you find any of the above topics very interesting or want to know about it, then please post a comment with specific topic name. I will make sure you get it.

I have also plans to take this project further.You can expect the future versions of Contact Management to have the following

  1. Email a friend
  2. Capture image of a friend and display it in very unique way
  3. Exploring on customizing a control and much better 3D ways to display it
  4. Creating, Changing and moving 3D objects in runtime

If you are finding any other problem in WPF or in Expression Blend or even if you find anything needs to improve in the application then you can always feel free to post a comment.

Happy Learning :)
Naveen Prabhu

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

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

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.

WPFReflection

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

Hi,

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.

VideoLibrary

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

VideoLibraryWithZoom

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

Hi,

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

OnMouseEnterTimeLine

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

OnMouseLeaveTimeLine

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)

AttachTimeLineToEvent
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 »

 
Follow

Get every new post delivered to your Inbox.