Tuesday, February 25, 2014

Building custom controls in WPF

Here I am going to briefly introduce with the types of custom controls one can build in WPF. Someone can ask why we need custom controls, if we can do everything with Styles and Control Templates ???

Well, I would say still there are scenarios where one may need custom controls. One of them can be, while creating reusable control which is composed of many other controls, i.e: I want to create a control for data entry purpose, which will take Temporary address and Permanent Address. Here I don’t want to copy/paste XAML code repeatedly for these two addresses. So, it’s better to create a one User Control and reuse it. Another scenario can be, when we need a functionality which is not provided by existing WPF controls, here custom control can be the best solution.

UserControl vs Control
Now before proceeding further, it is important to have a look at the two most common classes of WPF namely UserControl and Control.

UserControl should be chosen when you want to combine existing components, but here complex customizations won’t be supported. So, if you need lot of customizations or you want control templates, then Control class will be your choice. Best example can be themes, which requires Control class.

Now, let’s quickly dig into the code.
First step here is to add one User Control to the application. Please don't get confused with the Windows Form user control while adding because we want user control for our WPF application. So, select that:













Once your User Control is added, you will notice that the code behind file is inheriting a class UserControl as:












Now to understand it in better way, let's add one custom control as below:














After adding the control, if you will see Solution explorer, you will find that this time XAML file is not added for newly created custom control, but there is a new file under Themes as:















On opening the CustomControlAddress.cs, you will notice that it is inherited from Control class. Now before going forward, let’s go ahead and first populate our ResidentialDetails control. For simplicity purpose, I am taking here only two fields named Address and City as:












Above code snippet will give you a simple address control, which is best example of User control. Now let’s go ahead and modify our Custom control by modifying Generic.xaml as:












Finally comes the testing part. In order to make these control testable, we need to integrate them within our main xaml file as:









Once you are done with all these, you will get the desired output as:







Hope you got an idea on how to use what. Enjoy learning !!!

Friday, February 21, 2014

Binding Source Objects in WPF

Recently I received a request from one of the followers on ways to bind source objects. So, I thought it would be a nice topic for a post. Hence, it's here.

For a binding to work, there should be a source object. The selection of source object is totally dependent on the way binding is used. If no binding source is provided, then bydefault DataContext of an element is used. The most common way is to set DataContext on parent element and let it flow to all its children. But apart from this, there are 3 other ways by which one can point to source object: 

1) RelativeSource - Relative source is one of the property on a binding that can point to relative source markup extension which tells where the source can be found in hierarchy. In simple words, it is the relative path in the element hierarchy.

2) ElementName- Another way of specifying source is by using ElementName in which other element present in the current UI can be used as a source object. Here the source object has to be part of Visual tree.

3) Source - Another way is by using Source property on a binding. This source property has to point to some object reference and the only better way to get object reference down into the source property is that uses static resource which points to some object in a resource collection. 

Now let's quickly jump on to the code of each one of these. To make my example simple, I am taking only two fields named Employee Id and Employee Name and will display it in a WPF DataGrid.

As a ground work, I created a file to handle my data access part called DAL.cs. My all the business entities are kept in class called Employee and are populated in DAL class. Below is the snapshot of both my classes:

















And below is my XAML skeleton to display the data in the DataGrid:

















You might notice that by this time, I haven’t set the DataContext and ItemsSource property for my DataGrid. So, if you will run this application, your DataGrid will be empty with zero tupples. Going forward, I’ll pick each one of the binding sources to populate out DataGrid.
Let’s take Relative binding as the first one.

Using RelativeSource:
The common practice for setting DataContext in code-behind is by using the this keyword. What if, anyone don’t want to set this in code-behind by using this keyword. Well, the answer here is RelativeSource as shown below:

















Setting the RelativeSource to Self is equivalent to this. So, one need not to set DataContext in code-behind.

Using Source:
Here we will see binding Source property on a binding. Let’s say I want to set ItemsSource as Employees and don’t want to rely on the DataContext been set to something that expose to Employees collection. In that case, I can point explicitly to some Source object that contains my collection. And the typical way of doing this is by using Resources on the current view and further set that resource key as ItemsSource. Code will be:



















And you will see the output as:











Using ElementName:
To demonstrate this property, I am going to modify above sample a bit by adding a Delete button. This delete button will delete the selected row. To achieve this, I hooked a button and respective command as shown below:



















Please note, here DataContext of the button is coming from the parent which is Window itself. Here we are using CommandParameter because we need to send selected row as a parameter to our command. Point to note here is, we need to set ElementName property with our DataGrid because our selected employee will be part of DataGrid and the Path property with SelectedItem.

If everything is in place, you are ready to go. Hope you enjoyed learning!!!

Tuesday, February 18, 2014

Microsoft Introduces Bing Code Search Add-On For Visual Studio

Microsoft has launched the Bing Code Search add-on for Visual Studio, representing companionship between the Bing, Visual Studio and Microsoft Research divisions.
The Bing Code Search extension directly assimilates the code snippet search for C# with other languages, coming later into the Visual Studio. As this add-on is a part of the Visual Studio, programmers will be able to use it to search for the code samples from a number of web-based repositories including MSDN, StackOverflow, Donnetperls and CSharp411.
So, if you are using Microsoft Visual Studio for building apps, you can download the add-on, activate it, type the search string, press enter and you will get a couple of options that are suitable for your project. You can grab the add-on from the Visual Studio directory page.
However, the add-on can be used to search for the code samples anywhere on the Web as well; Microsoft says that the sites it has shortlisted should be “more than sufficient” for most of the queries.

Saturday, February 15, 2014

Overload resolution revisited in .Net 4.5

Overload resolution has always been an area of frequent attention for compiler team. So, once again there are some major changes done to make the compiler more intelligent. Let's have a look at the below snippet(picked from MSDN) first and try to predict the output:















Output in Visual Studio 2010: ExampleMethod: p2 is object
Output in Visual Studio 2012/13: ExampleMethod: p2 is string

Explanation of code: In above code, there are two overloads with a difference of 3rd parameter params and bit a different ordering of parameters.

Visual Studio 2010 picks the overload without params parameter whereas Visual Studio 2012 compiler is smarter and picks the overload which has more specific type.

If all your overloads do precisely the same thing, then this change will not be a problem. But in other cases, it may lead to crashes or exceptions.

So, going forward, be careful while offering method overloads.

Tuesday, February 11, 2014

Named parameters revisited in .Net 4.5

As most of you are aware that there are lot of language and compiler changes has happened with recent release of .Net, but all the issues will not arise until and unless you are recompiling your code. Once you recompile your code, these changes will be introduced regardless of which framework you target.

Today I am writing about one of these breaking changes happened in .Net 4.5. 
With earlier framework, named and optional parameter concept was introduced and unfortunately it was implemented incorrectly. In essence, there was a issue with the evaluation order of named parameter and will occur only when you are using methods as an argument. 

Let's have a look at this snippet taken from MSDN:













Expected output: A C B
Output in Visual Studio 2010: C B A
Output in Visual Studio 2012/2013: A C B

Hope by this time, you are convinced about this incorrectness.  Please note, here issue is with named parameters and has nothing to do with optional parameters. This issue is with the Visual Studio 2010 compiler which is giving the unexpected results.

Reason: Incorrect results are because named parameters are evaluated before the positional arguments. For both named and positional evaluation must be from left to right. This was the bug in VS 2010 and is addressed in VS 2012.

This is unlikely to cause a problem in your code until and unless you are calling methods in your argument list.
Suggestion: Avoid calling methods in argument list if order of execution is important for your application.

Note: ref and out parameters may also suffer from side effects due to this change.

Saturday, February 8, 2014

INotifyPropertyChanged revisited with .Net Framework 4.5

Prior to this post, I have already discussed few ways of handling INotifyPropertyChanged interface. Now you might be thinking what's next ?

Well, today I'll talk about much better and cleaner way of handling this interface, which is type-safe as well as less error prone. Till now, as a common practice, we were passing a property name as a parameter of our RaisedPropertyChanged method, which unfortunately has some demerits. 
Let's say, what if user changed the name of the property and forgot to change the parameter passed inside RaisedPropertyChanged method. Now you might say that we can get rid of this by using Reflection. Even I agree with that but again it comes with an additional associated cost. So, what's the solution now???

Enough of worries, this issue has been addressed in .Net 4.5, in which developer can get rid of this parameter passing approach. Impressed?

An attribute titled CallerMemberName relieves us from all the worries because now this attribute will retrieve method and property name for us. Let's have a look at the code now:












You will notice that the attribute is applied with the parameters supplied for RaisedPropertyChanged method. So, now the implementation of our property will be lot simpler as:















Now user is not forced to pass parameter to this RaisedPropertyChanged ,method. Hope you enjoyed learning this new feature.

Saturday, February 1, 2014

C# 6.0 with Visual Studio 2014

Today while surfing internet, I came across a very interesting interview snippet from Anders Hejlsberg and Charles Torre, in which they talked about the future version of C#, which will be 6.0. I hope most of you are aware that .Net version shipped with Visual Studio 2013 was the minor release with numbers as 4.5.1, which was just an upgrade of version 4.5. It is expected that all the major changes will be part of .Net 5.0 which will be shipped with Visual Studio 2014.

Another nice thing which came out is, C# 6.0 will be based on the new compiler Roslyn, which is written in C# itself rather than C++.

We can also expect some of the very cool features of C# 6.0 as:

  • Primary Constructors
  • Readonly auto properties
  • Static type using statements
  • Property expressions
  • Method expressions
  • Params for enumerables
  • Monadic null checking
  • Constructor type parameter inference
  • Inline declarations for out params

All the probable features of C# 6.0 will make life of developers bit more easier. The glimpse of all these features were provided at New Developers Conference recently held in London.

Well, so keep waiting till everything become reality ;)

Souces:
http://channel9.msdn.com/Events/Build/2013/9-006
http://adamralph.com/2013/12/06/ndc-diary-day-3/#more