Sunday, March 2, 2014

Converters in WPF

Converters give you a lot supremacy as it allows you to insert an object between a source and a target object. At high level, converters are a chunk of custom code that hooked up through the binding and data will flow via that converter. So, whenever data is flown from source to target, one can change the value or can change the type of object that needs to be set on target property.

So, whenever data travels from source to target, it can be transformed in two ways:

Data value: Here transformation will be done with just the value by keeping the data type intact. For example, for number fields, you can transform value to floating point number to an integer, by keeping the actual value as a float.

Data type: One can also transform the data type. For example, setting a style based on some Boolean flag, this is one of the most common example. Isn't it?

Defining a converter:
Defining any converter requires implementation of IValueConverter interface in a class. This interface has two methods:

Convert: Is called when data is flowing from source to the target
ConvertBack: Is called when data is flowing from target to source. It is basically useful in two-way binding scenarios

Where to place converters:
To implement IValueConverter, one has to create a class and then put the instance of that class in a ResourceDictionary within your UI.

How to use:
Once your class is part of ResourceDictionary, then you can point to the instance of converter using the Converter property of Binding, along with StaticResource markup extension.

Using Code:
Before digging into the code, let’s discuss on what I want to achieve with below code snippet. Whenever value entered by the user is negative, I want to display 0 with * as a final amount. 

So, let’s start by creating a class called RoundingOffConverter and inherit IValueConverter as shown below:

In above class, Convert method will be called when direction of data flow is from source to target. value object is the one, which we are going to set here, targetType will tell you the type of target property, next is optional parameter and last one is for culture.

ConvertBack method will be called when you have two-way data binding and direction of data flow is from target to source object.

Code for using Data Value:
So, to achieve our need, let’s replace default convert methods to our own implementation as:









To make this example simple, I am simply creating 2 properties in code behind as:




















Now coming to XAML, first I need to add a reference of my converter class and then need to add that as a resource. It goes, here:




Once the reference is added, I have to bind this converter to my TextBox object as:

Once everything is in place, let’s run this application. You will find below output:












Code for using Data Type: Here aim is to select a style based on a Boolean property or in other words user want to change the color of a text box based on checkbox status. So let’s go ahead and write our BoolToStyleConverter.

As before, quickly create a class for this new converter as:
















Next step is to create styles in App.xaml. It can be done as:













Now in order to use above styles in application, one has to add these as a Window Resources as shown below:




Once the converter is added to resources, next step is to use this converter in our UI. So, let’s add:





We are done. Now quickly run this application and you will find color change based on text box as:

















Hope this tutorial on converter was useful.

Saturday, March 1, 2014

UpdateSourceTrigger in WPF

This is a property on a binding that controls the data flow from target to the source and used in two-way databinding scenarios. The default mode is when focus changes but there are number of other options available, which we will see in this article.

Data trigger scenarios:
Let’s talk about some of the data trigger scenarios. By default, modified values in the binding controls only get pushed down when we do activity related to focus change like tab out, minimizing and maximizing window, etc.

·     In some scenarios we want to update values as quickly as possible, or let’s say with every key stoke.  So, to achieve such kind of scenarios Microsoft provided UpdateSourceTrigger

Properties available with UpdateSourceTrigger:
  • Default – This is the default value and it means a lost focus for most of the controls
  • LostFocus – Value updation will be on hold until the focus moves out of control
  • PropertyChanged – Value updation will happen whenever a target property changes. It usually happen on every key stoke
  • Explicit - Used to defer source updates until user do it forcibly by click on any button or so.

Default vs LostFocus 
Default and LostFocus mean the same thing for most of the controls with a exception of DataGrid. For DataGrid:
o                Lost Focus: Cell lost focus
o                Default: Row lost focus

Now let’s have a look at the example and sample code:

    <Grid>
        .........
        <TextBlock Text="Source:" Width="auto"/>
        <TextBox Name="SourceText" Width="160" Height="30" Margin="48,0,44,82" />
        <TextBlock Text="Target:" Grid.Column="1" Width="auto"/>
        <TextBox Name="TargetText" Width="160" Height="30"
                 Grid.Column="1" Margin="44,0,47,82" />
    </Grid>


In above code I am creating 2 TextBlocks and 2 TextBoxes, which will be shown as:







Please note, as of now I haven’t done any binding on my textboxes. As a next step, let’s pick properties of UpdateSourceTrigger and see what each one of does.

Default: When user will change value in Source textbox, value will automatically get updated in Target textbox. BUT when user will modify value in Target textbox, it won’t reflect in Source textbox, until lost focus happens.
Code:
<Grid>
         .......
        <TextBlock Text="Source:" Width="auto"/>
        <TextBox Name="SourceText" Width="160" Height="30" Margin="48,0,44,82" />
        <TextBlock Text="Target:" Grid.Column="1" Width="auto"/>
        <TextBox Name="TargetText" Width="160" Height="30"
                 Text="{Binding ElementName=SourceText, Path=Text,UpdateSourceTrigger=Default}"
                 Grid.Column="1" Margin="44,0,47,82" />
    </Grid>

Output:
When user types in Source TextBox 





When user types in Target TextBox :





LostFocus: As I mentioned earlier, except DataGrid, LostFocus behaves same for all the controls as Default property.

Code:
<Grid>
        .......
        <TextBlock Text="Source:" Width="auto"/>
        <TextBox Name="SourceText" Width="160" Height="30" Margin="48,0,44,82" />
        <TextBlock Text="Target:" Grid.Column="1" Width="auto"/>
        <TextBox Name="TargetText" Width="160" Height="30"
                 Text="{Binding ElementName=SourceText, Path=Text,UpdateSourceTrigger=LostFocus}"
                 Grid.Column="1" Margin="44,0,47,82" />
    </Grid>

Output:
Here output will be same as above case (Default) as it is TextBox.

PropertyChanged: If UpdateSourceTrigger property is set to PropertyChanged, then everytime both Source and Target will be in sync. In another words, updating Source TextBox will update Target TextBox on every key stroke and same proves true if value is updated in Target TextBox.
Code:
<Grid>
         .........
        <TextBlock Text="Source:" Width="auto"/>
        <TextBox Name="SourceText" Width="160" Height="30" Margin="48,0,44,82" />
        <TextBlock Text="Target:" Grid.Column="1" Width="auto"/>
        <TextBox Name="TargetText" Width="160" Height="30"
                 Text="{Binding ElementName=SourceText, Path=Text,UpdateSourceTrigger=PropertyChanged}"
                 Grid.Column="1" Margin="44,0,47,82" />
    </Grid>

Output:
When user types in Source TextBox:





When user types in Target TextBox:





After reading this article, hope you got a clear understanding on UpdateSourceProperty.
Enjoy learning !!!


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