Sunday, March 16, 2014

Customizing debugging session - Part II

Continuing to my previous article on 'Customizing debugging session', we can further control on how properties and fields appear in our debugger window. Based on our debugging requirement, we can show and hide properties in our debugging session using one of the useful attribute named DebuggerBrowsableAttribute.

Let’s go ahead and see debug window for one of the code snippet:

In above image you will notice that by default list of Awards is not in expanded form. In order to view the values of awards, one needs to expand that forcibly either by hovering the mouse or by click on the plus symbol, which will result in below screenshot:

How to hide unwanted properties during debugging session? What if a developer is not interested in viewing employee’s branch?

Well, that unwanted property can be made hidden by using DebuggerBrowsableState as Never as shown below:

Now let’s run the code and check, whether it is hidden:

As expected, you land up with above debugger window with Branch property hidden. Great !!! Let's move to next question...

Is there any way to expand list of awards automatically in my debugger window?
Yes, we can. Using the DebuggerBrowsableState as RootHidden as shown below:

On debugging the application, you will notice that list of awards are in expanded state now as below:

Hope you enjoyed playing with your favorite debugger window.

Wednesday, March 12, 2014

Customizing debugging session - Part I

I hope, being a developer everyone needs to debug their code at least once a day even if it is a very small snippet. Frankly speaking, sometimes it becomes very frustrating when we are looking for a value of particular property or let’s say very few properties of a huge object and it gets TIMEOUT. Uhhh !!!

This time, we feel like there should be some easy way to navigate to that particular property instead of going to the object and clicking on plus symbol to reach the required property. Well, let’s understand it via code:

Aim: I have an Employee class with two members as EmployeeName and BranchName. I want to know the name and branch of an Employee during my debugging session. So, I start debugging and lend up on below screen:

Now in order to view the required details, I need to expand the employee object as shown in below screenshot:

Now first question is, is there any way to display customized message in debugger window? Answer would be YES. One simple override method will do this job for us.

Let’s go ahead and override the ToString method as shown below:

Now launch the application and you will be able to view your text during debugging as shown below:

Point to understand here is, by default Visual Studio uses ToString method in the debugger. Please note, overriding the method will only display the message and it won’t affect the values of your employee object. In other words, on click on plus symbol in debugger window, you will still be able to view employee’s branch and name.

Well, it’s time to move for next question which I feel is very important concept.
Second question is, is there any way to display value of required property instead of customized message? Again answer is a big YES. A simple attribute named DebuggerDisplay will rescue you.

Let’s quickly jump on the code to check, how to use this attribute:

As you can see that the attribute can be applied to class level and takes a string as a parameter and inside the string, one can reference the member variables of the class using curly braces. Now time to see, what debugger will show us:

Isn’t it a cool feature? Hope you will use it :)

One can use this DebuggerDisplay attribute with classes, enums, delegates, structs, fields, properties as well as with assemblies.

When to use this DebuggerDisplay attribute?
One certainly can’t use it all the time due to its maintenance overhead. I would recommend it to be used at class level and can be at properties level, if your properties are complex and less self-explanatory. Enjoy debugging!!!

Saturday, March 8, 2014

FallbackValue and TargetNullValue

One of the ability of binding in WPF is the ability to support Fallback values. Fallback values are used when a binding comes up with an un-appropriate value which in turn can't be set on binding target. There are 2 types of Fallback values:

    As its name communicate itself that when a source object’s property is null, then what is the alternate value you want to set for the target. So, whatever value is set for TargetNullValue, it will be set for target. Pretty simple, isn't it ?

2   FallbackValue
    This is used when a binding cannot come up with a value at all, based on the the data source and the path. Or in other words, FallbackValue is used when the property binded with source is not at all available. In that case, value supplied to FallbackValue will be considered at the target end.

Getting into the code: 
Now, let’s jump on to the code on how to use both of these. Here aim is to bind the given text box with EmployeeName property.

My code behind class contain just the basic code to create a property for employee name, so that we can bind it with TextBox. Here goes the code:

And my XAML file contains below code:

Till this point, we haven’t done anything extra. It’s pretty simple and self-explanatory code. Let’s go ahead and quickly change the code a bit.

Demonstration of TargetNullValue:
As I mentioned earlier, TargetNullValue comes into picture only when your source object is null. To make source object null, let’s go ahead and do the minor changes into the code, as:


Now, next step is to set the value for TextBox, which will be displayed if source object (in our case source object is EmployeeName) is null. Let’s modify XAML file for this:

Now, when you will run the application, you will find the TargetNullValue is set for the TextBox as:

Demonstration of FallbackValue: 
This FallbackValue will play its role when binding is not able to resolve the source. So, for this missing source, one can set the default value for the target. Let’s have a look at the code:

In above code, instead of binding TextBox to EmployeeName, I am binding it to EmployeeNames which is not the correct property as no such property is defined with this name. Hence my FallbackValue will come into picture and will give us the below output:

Hope this article was useful :)

Wednesday, March 5, 2014

Gotcha with StringFormat

Hope most of you have used StringFormat property on your binding to render the formatted value on the user interface. But are you aware about one of its secret. Well before revealing that secret, let’s have a look at how StringFormat works with binding.

Scenario problem: I am taking an example scenario, in which my text box will display amount till three decimals. 

Now there are multiple ways to achieve this. One way can be by using Converters, another way can be by using StringFormat along with TextBox binding. Perhaps there can be more ways apart from these two ;)

In below sample I am going to take StringFormat trick to achieve this and code to perform this operation is very straight forward as:

<TextBox Text="{Binding Amount,StringFormat=f3}" />

With above code, whenever you will lost focus from your TextBox, given amount will be displayed as three decimal points. Till here everything is perfect as expected BUT with one downsize.

Important point on StringFormat: 
What one sees on the screen is not the actual value that will be stored in the storage and can be different from the underlined value. But if this is really a requirement on what we want to show to the user then it’s up to developer to manage such inconsistencies.

Gotcha with StringFormat:
Now time came to know about that GOTCHA. If you want to add UpdateSourceTrigger property = PropertyChanged along with your StringFormat, then guess what will happen???

<TextBox  Text="{Binding Amount, UpdateSourceTrigger=PropertyChanged, StringFormat=f3}"/>

To understand this issue, let’s go step by step.
Step 1: Run the application and you will get below output.

Step 2: Enter value in the text box as 35.45. You will land up with below screen:

Explanation: Please note, you have applied UpdateSourceTrigger=PropertyChanged. So, as soon as you will hit a keyboard key, immediately StringFormat will be called due to change in target property and sets the underlined source property. Our source property raises a PropertyChanged event that forces the binding to re-bind and re-render based on the StringFormat. 

Problem occurs with fast input scenarios as shown in above screenshot and you will end up with RED rectangle.
Reason: After each key stroke, it is re-rendering the value of a given text box.

Step 3: Click on Save button in order to fire the loose focus from text box as shown below:

Explanation: As per the StringFormat property, given text box should be able to change the value to required precession. But it doesn’t happen. 
Reason: Due to UpdateSourceTrigger=PropertyChanged

One should avoid using UpdateSourceTrigger=PropertyChanged with StringFormat, due to this re-rendering issue.

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:

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

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

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.

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

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

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 !!!