Routed Event in WPF – Introduction
Posted by Manas Patnaik in WPF on October 2, 2010
Till date we were acquainted with normal event which are basics of Win Form Applications.WPF introduces a new concept called as Routed Event .So here we will have a brief intro for this new feature and comparison between CLR Events and Routed Events.We will not start with definition , instead we will go back to old methods of CLR event and try to achieve something funny but logically meaningful.
Track Mouse Challenge (My niece 6 yrs old was tester , Still i failed )
So a very simple logic , Whenever the mouse moves with in the panel the Status Label should display as “With in Panel” or else “Outside Panel”.So what we need to do is ,track it with Mouse Move and Mouse Leave events .The logic and code follows as bellow.
- private void pnlContainer_MouseMove(object sender, MouseEventArgs e)
- {
- pnlContainer.BackColor = Color.Red;
- lblMouseLocation.Text= “With in Panel”;
- }
- private void pnlContainer_MouseLeave(object sender, EventArgs e)
- {
- pnlContainer.BackColor = Color.Cyan;
- lblMouseLocation.Text = “Ouside Panel”;
- }
Very Simple .Lets Run.But the results are not as of requirement .So
My Niece’s Bug Report
“When Ever the Mouse moves over the Black Board (Image Control) , status (Label Control) shows Outside Panel “ and that too logged on High Priority mode :).
Logically it should not happen .To patch it up in the end i attached event handler to the Image control .But suppose the panel contains more than one image or controls then how pathetic it will be to attach event to all .
Year 2010 , I tried to implement same logic with WPF and it surprised me.
Track Mouse Challenge , in WPF
Now with WPF i emulate the same logic as in my previous WinForm application and it worked .
and the code followed exactly same as above.
- private void pnlContainer_MouseMove(object sender, MouseEventArgs e)
- {
- pnlContainer.Background = Brushes.Red;
- lblMouseLocation.Content = “With in Panel”;
- }
- private void pnlContainer_MouseLeave(object sender, MouseEventArgs e)
- {
- pnlContainer.Background = Brushes.Cyan;
- lblMouseLocation.Content = “With in Panel”;
- }
e
Download the compiled programs and Check it.
This is exactly where WPF introduces you to Routed Event.
What Is Routed Events
Routed events are the events that travel through the parent/ Child container of a control with raising their events .The movement logic known as Routing Strategy (We will Digg into it in my next posts).
So events can also be captured at parent or child container instead of the particular control which invokes it.
Scenario Of Use
I know you will not agree with the scenario as mentioned above .
So some practical usage ,Consider a case of a normal calculator which contains 10 Numeric Button and Logical Operations .It is normal to write behind each control event , but what about code readability and scattered logic.Why should not we write a common logic part behind the parent container.
Another simple usage is YEs,No,Cancel button used in all our form.
I can handle events of buttons in the container Boarder.
Technical Difference From CLR Events
WPF UI is a composite architecture based , means a control can be consists of several other controls or resource .Lets have a look at the document outline of the TrackMouse application.The Border (Resembles to Panel in Winform) contains the image control element.
The events are also followed as of the VisualTree above .The events of Image Element can be handled at its parent element Border.In Mouse Track program , Mouse Move of Image is a Routed event which invokes the parent Border Mouse move event also.Try to debug the code .
I know the Technical details are not sufficient and the scope of the particular post doesn’t allow it .In my next posts i will cover the Routing Events and Routing Strategy in depth.
Code for this Article -Routed Event Intro Download
That’s it for now , i hope you liked my niece’s intelligence :).
Event Handling in WPF
Posted by Manas Patnaik in WPF on September 30, 2010
Events in WPF works same as in Win Form application except some new concept such as Routed Event ( I will blog it in next post).So directly we can jump to the code to add simple events to application as well as Window(Forms in WPF are called as Window ,for XBAP it called as Page).
There are 2 ways of adding events
- Declarative Way ( XAML Approach )
- Code Way (Conventional as in Win form / Code Approach)
So consider the scenario bellow and the way to do it in both ways
Scenario 1 –: On Start of our Application we will show the application details.
Through XAML
As we should on load of application the event must be declared in the app.XAML or app.xaml.cs.Write the the event name we want to invoke , the intellisense will prompt as follows
Once you click
, it will add a handler to the app.xaml.cs .And there we will have the application information.
| What is Event Handler ? |
- /// Interaction logic for App.xaml
- /// </summary>
- public partial class App : Application
- {
- private void Application_Startup(object sender, StartupEventArgs e)
- {
- MessageBox.Show(Environment.Version + “\n” + Environment.UserName
- ,“My First WPF Application”);
- }
- }
Through CODE –:
As the OnStartup is application related event we will override in the app.xaml.cs.
- protected override void OnStartup(StartupEventArgs e)
- {
- MessageBox.Show(Environment.Version + “\n” + Environment.UserName
- , “My First WPF Application”);
- }
Scenario 2 –: On Button Click display application information (Attaching a event to a method)
Through XAML –:
First we will create a EventHandaler in the the window , as bellow .
- public partial class MyFirstWindow : Window
- {
- public MyFirstWindow()
- {
- InitializeComponent();
- }
- private void ShowApplicationInfo(object sender,RoutedEventArgs e)
- {
- MessageBox.Show(Environment.Version + “\n” + Environment.UserName
- ,“My First WPF Application”);
- }
- }
Now we will attach the event to the button click in through xaml .
So the final Xaml code will look like this.
- <Grid>
- <Label>My First WPF Application</Label>
- <Button Content=”Show About” Height=”50″ HorizontalAlignment=”Left” Margin=”71,78,0,0″
- Name=”btnShowAbout” VerticalAlignment=”Top” Width=”143″
- Click=”ShowApplicationInfo”
- />
- </Grid>
Through CODE–:
Code way is same as previous we need to attach the event to the handler on load.
- private void ShowApplicationInfo(object sender,RoutedEventArgs e)
- {
- MessageBox.Show(Environment.Version + “\n” + Environment.UserName
- ,“My First WPF Application”);
- }
- private void Window_Loaded(object sender, RoutedEventArgs e)
- {
- btnShowAbout.Click += new RoutedEventHandler(ShowApplicationInfo);
- }
That’s it .
Getting Into WPF
Posted by Manas Patnaik in WPF on September 29, 2010
Learning a new programming platform is never easy until unless somebody is really inspired.WPF (Windows Presentation Foundation ) is quite convincing if you look at its prospective and the capability it gives to user.This new graphical subsystem from Microsoft relies on Direct X for rendering instead of GDI.So the advantage this declarative programming model is Resolution Independent provides extensive integration with independent technology (Text to speech , 3d animation ,video etc),Hardware acceleration with Direct 3d and most useful complete customization of controls.
Wpf applications development can be of two type
- Windows Based Application
- Browser Based Application (XBAP)
| What is Declarative Programming ? |
This Blog post is about my experience with first WPF application , a simple application with basic understanding.
Create a WPF Project :
Open Visual Studio and Select WPF Application .Provide a Name “StartWithWpf” and click Ok .
Have a look at the source folder , It contains a default MainWindows.xaml and App.xaml.So the XAML Markup drives WPF application with similar syntax of XML (Read More about XAML and Syntax) .A complied form of XAML is known as BAML.
Digging Into APP.Xaml:
The App.Xaml (Application class )is the entry point for the application .We can write as code behind application class or in the mark-up.The declarative Mark-up is must for XBAP.
Code Snippet
- <Application
- xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
- xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
- x:Class=”StartWithWpf.App”
- StartupUri=”MainWindow.xaml”>
- </Application>
So the app.xaml need above lines to run a project.These are the Attributes of Application .
xmlns –:Defines the Namespace for the Application
xmlns : x-:Defines the additional namespace for the application
Above both attributes direct to the specification required to be referenced for xaml.You can find out some additional references as you add your some custom namespaces.
Adding a Form:
Now lets add a Form , here it is Windows (instead of Form as in WinApp).So adding a Window named “MyFirstWindow”.![]()
Now the look at the Window , we have added.
I will change the Title property and add a label to the Grid Layout.(Layouts are very important in WPF ).
- <Window x:Class=”StartWithWpf.MyFirstWindow”
- xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
- xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
- Title=”Home” Height=”300″ Width=”300″
- >
- <Grid>
- <Label> My First WPF Application </Label>
- </Grid>
- </Window>
Now to Run the application i will go to App.xaml and Change the StartUpUri attribute to “MyFirstWindow.xaml”.Lets run it and you are ready with your first WPF application.A simple but fair start :).
Bing With HTML 5
Posted by Manas Patnaik in Latest in the air on September 16, 2010
Bing in HTML5 could be Microsoft’s response to Google’s instant search, and we could likely see this being released by the first quarter of next year, right around the Internet Explorer 9 launch.
Watch it :
Start With SQL Compact Edition (SQL CE)
Posted by Manas Patnaik in SQLServer on July 26, 2010
Hi Further on my previous article for introduction to SQLCE (Check it), i am going to walk you through to SQLCE with a very simple application.This sample will guide you from adding a local database to creating a connection and some CRUD operations.
Adding a SQLCE database to Project
- Add a new Item to the project .
![]()
- Select the DATA option and select local Database option.Provide a database name and click OK
- You can find the local Database as bellow.
![]()
- You need to have a reference to the SqlServerce.dll .
- To browse the Database , Right Click on Model.sdf and click Open.Then you will be able to get the table details.To add a new table Right click on Tables and click on Add table.In this case i have created 2 tables as shown in figure.
Creating a connection from C# project
The System.Data.SqlServerCe namespace is the .NET Compact Framework Data Provider for SQL Server CE. WithSystem.Data.SqlServerCe, you can create and manage SQL Server Mobile databases on a smart device and also establish connections to SQL Server databases.
-
public void Connect()
-
{ -
string FileName="Model.sdf";
-
SqlCeConnection con=new SqlCeConnection(@"Data Source=|DataDirectory|\"+ filename +".sdf;Password=123" );
-
con.Open();
-
}
Retrieving Data
The following code perform simple Data retrieval from the SDF file based on the sqlcecommand.
private void RetriveData() { string FileName="Model.sdf"; SqlCeConnection con = new SqlCeConnection(@"Data Source=|DataDirectory|\" + FileName + ".sdf;Password=123"); con.Open(); sqlceda.Fill(dsData); gvEmpMaster.DataSource = ds.Tables[0]; }
Get the sample Application code
The sample application stimulate a typical windows based application using sql CE.This application consist of a wireframe database (model.sdf) which will be used to create other files and based on it the user can insert data and later retrieve it.
Sample Application Download
SQL Server CE (compact Edition)
Posted by Manas Patnaik in SQLServer on July 25, 2010
Good news for small application developers , Microsoft released compact version of SQLSERVER (SQLCE 4.0 CTP1 ) for desktop ,web as well as for mobiles.This embedded database format is a huge relief from cumbersome and hectic installation of sql server .Although this was from long back still its reliability and features introduced in 4.0 CTP1 is awesome.I would like to introduce the some review and remarks on it in a very short manner.
Sql Server Compact Edition(SQLCE) is a embedded database for Mobile,Desktop and Asp.Net based projects.
For Whom :
- If you are going to develop small/Mid level office application.
- If you want hassle free installation of Database (Copy and Paste option)
What is the Latest Version :
Latest Version : 4.00 CTP1 Download
Last Release : 3.5 SP 2 Download
Some Facts -:
- Supports Data up to 4 GB.
- File based code free Database
- Supports concurrent multiple connection from .
- Runs in process of Application (Other MS sql Editions used to have separate services)
- SQL CE databases reside in a single .sdf file.
- The .sdf files / Database can be password protected as well as encrypted.
- SQL CE databases are ACID-compliant. Like Microsoft SQL Server,
- SQL CE supports transactions, referential integrity constraints, locking as well as multiple connections to the database store
Advantages
- Very Small footprint(2 to 2.05 MB).
- File based Database with enhanced security option.
- All you need is Copying of binary to your installation path.
- Easily Upgradeable to higher versions (MSSQL Express etc..)
Limitations
- Doesn’t support Stored Procedures, also they don’t have plan for it. Go through the nice article from Steve.Lasker Read it.
Just have a look at the detailed comparison matrix with sqlExpress Edition.
Hi World ..
Posted by Manas Patnaik in General on July 17, 2010
Hi all , this is my first blog after a long persue from my friends .It is always good to start late instead of not doing it.Ok my self Manas as you can find from domain name , i am working in MNC , India as Technology Analyst and loves dancing.
Before i took up blogging i asked my self so many time times “Why should i blog” .
As i got the answers after a lot of in fight with my consensus i want to share with you. As a human and as a engineer you need to improve and you need to excel in what ever you do and this improvement can be achieved if you analyse the work you have done and the experience you learned. I would like to share one quote :
“If you re-read your work, you can avoid a great deal of repetition and can achieve improvement in future endeavor ”
So thats it 🙂 now i am ready to share it with me as well as all of you .
I am going to write about my work experience related to Technology , life , business and what ever i feel i need to share with all.Of course i need you feed back and one line comment that will help me to do better .
Keep Reading .
Hello world!
Posted by Manas Patnaik in Uncategorized on June 24, 2010
Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!
Recent Comments