Textblock showing full text in tooltip when text truncated inside control

June 3, 2012 1 comment

This post describes implementation of custom textblock which will show the full text of the textblock in tooltip when Text can not be shown fully inside the given width of textblock control.

Textblock has property named “TextTrimming”. Value set for this property defines how text is trimmed when it overflows from the edge of Textblock. When “TextTrimming” property is set to “WordEllipsis’ / “CharacterEllipsis” and text value can not be shown fully in given width then text will truncate with “…” (i.e. ellipsis) shown at the end of text. Now one option to show the full text to user is through Tooltip. This can easily be achieved by binding text value as tooltip. However, the heck is showing full text value as tooltip only when needed i.e. when text has been truncated inside Textblock.

Unfortunately, Textblock doesn’t provide any property to indicate that text has been truncated / trimmed. Hence, we need to detect when the text has been truncated i.e. text size has increased beyond the width of textblock’s width. So now the problem is measuring width of text considering text settings applied. “FormattedText” class provided by Microsoft can help us for this. “FormattedText” takes into consideration FontSize, FontStyle, FontWeight, FlowDirection, current culture, etc. while calculating the width of text. Following code snippet shows how to measure text width using “FormattedText”.

Typeface typeface = new Typeface(this.FontFamily,

// FormattedText is used to measure the whole width of the text held up by this container.
FormattedText formmatedText = new FormattedText(

After getting the FormattedText object, just Check

formmatedText.Width > this.ActualWidth

to determine whether text has been truncated or not.

I have attached herewith the full implementation of Custom TextBox class (TextBoxEx) in a word file. In the implementation when Tooltip is opening, it is checking whether text has truncated or not. If text has not truncated then tooltip won’t be displayed (as it is not necessary because full text is anyway visible). Also, in order to show the tooltip, text property of the Textblock should be bound with the tooltip.

ToolTip="{Binding Path=Text, RelativeSource={RelativeSource self}}"

It is pretty obvious that if binding for tooltip is not set then this control will not work.

This one is pretty simple fix for the problem and it works well in the scenarios I have tested so far. Any feedback/bug/enhancement request on this is welcome.


Subclassing WPF user control

September 21, 2011 3 comments

It is not very common to do User Control subclassing but if you have some compelling reason to do so then following detail explains how to do it with WPF User Control. Due to xaml, user control subclassing in WPF becomes little tricky. Following steps explain the procedure :

1. Create a base control as simple c# class and not WPF user control. Derive this base class from UserControl.

    public class ESQBaseControl : UserControl
		#region Constructor
        protected ESQBaseControl()
            // protected constructor is required so that derived controls can have default parameterless constructor which is needed for xaml 
            // also protected constructor will ensure that new control creation always use constructor by passing parameters (e.g. in this example passing of string parameter is must in order to construct control)

        public ESQBaseControl(string info)
		#region base implementation
		public virtual void SomeOperation()


2. Base class will not have UI implementation because of the absence of xaml. So time to build some UI for our control in concrete control xaml.

	<view:ESQBaseControl x:Class="<namespace>.ESQConcreteControl"
             xmlns:view="clr-namespace:<namespace in which base control resides>"
             d:DesignHeight="300" d:DesignWidth="300">

			<Label Content="My Control"/>
			<TextBox x:Name="MyTextBox" Grid.Row="1" Text="Some Text"/>

In above code note that whole xaml has been wrapped inside BaseControl class while class name inside xaml definition is given of the concrete class.

3. Finally, inside the code behind file user control’s concrete logic can be implemented :

	public partial class ESQConcreteControl : ESQBaseControl
        #region Constructor

        public ESQConcreteControl(string info) : base(info)
		#region Control implementation
		public override void SomeOperation()
			myTextBox.Text = "Hello World!!";

Hope this helps!!

Interop & IDataErrorInfo

September 17, 2011 Leave a comment

Despite of all the interop support available sometimes you will still come across some tricky issues which will be difficult to overcome. One such problem I faced recently. I had to configure the Dialog with MFC PropertySheet control. This PropertySheet control was holding few Property pages. These property pages didn’t had any MFC controls as content but hosting the user controls developed in WPF. First I will write very briefly about how to load the WPF user control inside the MFC container and then I will explain about my tricky problem and how I fixed it.

Hosting of WPF user control as content of PropertyPage wasn’t that challenging. In order to host the WPF content inside property page, first HwndSource needs to be configured. In order to create HwndSource, first you need to create HwndSourceParameter. Typical configuration for HwndSourceParameter can be as under :

System::Windows::Interop::HwndSourceParameters^ sourceParams = gcnew System::Windows::Interop::HwndSourceParameters (<Window Name>);

// X position where WPF content to be placed
sourceParams->PositionX = x;
// Y position where WPF content to be placed
sourceParams->PositionY = y;
// height of the WPF content
sourceParams->Height = height;
// width of the WPF content
sourceParams->Width = width;
// Handle for the Parent window inside which WPF content to be hosted
sourceParams->ParentWindow = IntPtr(parent);
// style attributes as needed (“WS_TABSTOP” style needs to be set if WPF content needs to get focus while tabbing
sourceParams->WindowStyle = WS_VISIBLE | WS_CHILD | WS_TABSTOP;

Another important property for HwndSourceParams is “ResetFocusMode”. Default value for this property is “Auto”. Setting this property to “Auto” makes sure that when when the PropertySheet control (in my case) looses the focus and receives focus back the control which had focus prior to loosing focus retains the focus back. If you set this property to “None” then, none of the controls inside the page will have focus when propertysheet control receives the focus.

// now create HwndSource using this parameters
System::Windows::Interop::HwndSource^ hwndSource = gcnew HwndSource(*sourceParams)

Now suppose I have a WPF user control named “PageUserControl” then create instance of this user control.

PageContentUserControl^ pageContent = gcnew PageContentUserControl();
//Now set this user control as RootVisual of HwndSource object. 
hwndSource->RootVisual = pageContent ;

With above code in place it is possible to host the WPF content inside MFC control. This is just basic information which one should know in order to host the WPF content inside MFC container however somewhat plumbing work will be needed depending upon MFC container control in which you are placing the WPF control.

After hosting the control I had one more issue to deal with. My User control developed in WPF had few checkboxes, text boxes, etc. as it’s content. In order to validate my inputs and giving visual indication about the data validation failure, I had implemented interface “IDataErrorInfo”. (Now how this interface is implemented and how it works is not covered in this Post. Google it to find more on it)

When “IDataErrorInfo” interface implemented and bound value to the control is invalid, control will have a red border around it to indicate user about the validation failure. Also, when you set focus on the control like check box through tabbing, you will not be able to see the dotted line around check box when it receives the focus. Following figure shows the focus styles for each case. When User Control is hosted within MFC container, you will assume that “IDataErrorInfo” implementation should work but infect it won’t.

The problem of not being able to see all such decoration is absence of Adorner layer. All these error templates and focus styles etc. are drawn inside the AdornerLayer. The WPF window has an AdornerLayer by default, so we can always see validation errors in WPF. When hosting a user control in MFC, adornerlayer is not available by default and need to add an AdornerLayer into your UserControl to support adorners.

So in order to view all such Focus styles / Error template styles, we need to decorate the UserControl with AdornerDecorator. So following code should do the fix for you :

<UserControl x:Class="TestPjt.TestUC"
             d:DesignHeight="50" d:DesignWidth="300">
              <TextBox x:Name="txtbox"/>

This fix will start showing the expected focus and error template style for each control. HTH!!

Destructor – Finalize & IDispose

October 3, 2010 1 comment

This post is about techniques on how managed/unmanaged resources used/referenced by objects can be released. There are two ways to do this. They are namely,

1. Implement IDisposable

2. Implement Destructor (Finalize) for object.

This post describes how both gets implemented and what are the pros n cons of both ways.

Destructor & Finalize :

Destructor in managed code can be written in similar way as unmanaged code.

 class TestClass
    ~TestClass()  // destructor implementation
        // free resources

When destructor is written in managed code, it ultimately translates into following code post compilation :

protected override void Finalize()
        // free resources here

(So this means both destructor & Finalize are same in managed context.)

How destructor works :

When reference count becomes zero for the object which implements destructor then that object is marked for collection and object is put into the finalization queue. When garbage collector start collecting the memory, at that time destructor for the objects in the finalization queue will be called. When destructor is called then unmanaged resources can be freed and object memory is collected.

IDispose :

IDispose is basically .net framework interface which defines the method to release the allocated resources. Inside the interface method implementation should be present to release the resources.

How IDispose work :

Let’s consider following code to understand how IDispose and destructor work in tandem. In following example “TestClass” implements IDisposable and also implements destructor. This code uses managed resource StreamReader and unmanaged some Integer pointer which needs to be freed before object is freed after it’s use.

    public class TestClass: IDisposable
        // Pointer to an external unmanaged resource.
        private IntPtr intPointer;
        // managed resource
        System.IO.StreamReader stream;
        // Track whether Dispose has been called.
        private bool disposed = false;

        // The class constructor.
        public TestClass()
            this.intPointer = /* assign some integer pointer*/;
            stream = new System.IO.StreamReader(@"C:\Test.txt");

        // Implement IDisposable.
        public void Dispose()
            // as dispose has already been called supress finalizer

        private void Dispose(bool disposing)
                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                    // Dispose managed resources.

                // dispose unmanaged resources here.
                intPointer = IntPtr.Zero;

                // Note disposing has been done.
                disposed = true;


        // destructor

Dispose method with private accessor is being called from both interface Dispose method as well as destructor. When Dispose is called, first managed resource is freed and after that unmanaged resource is freed. Thus both managed and unmanaged resources are freed. After clearing the resources, GC.SupressFinalize is called so that the object is removed from finalize queue.

Now the question is when IDisposable and destructor are doing the same thing then why two separate things are required. Answer of this question lies in the nature of the execution of both these implementation.

Difference between Descturctor-Finalize & IDisposable :

Destructor is not deterministic way of freeing the resource. When object with destructor is marked for garbage collection, it will be put inside the finalization queue. Whenever garbage collector runs, object inside the finalization queue will free the resources. Because time when the garbage collector will run is not sure, it can not be predicted when resources will be freed.

IDisposable is deterministic way of freeing the resource. IDisposable is useful when some shared resources or some high memory consuming resources needs to be freed. Calling the dispose on the object will ensure that resources are freed immediately (however memory associated to the object may not get collected until garbage collector runs).

Some Finer points about Destructor-finalize & IDisposable :

Destructor – Finalize :

  1. Finalize is not a good option to use when shared resources / memory consuming resources needs to be freed because of it’s non deterministic nature.
  2. Releasing the resources using Finalize is costly from performance point of view. Why implementing Finalize is costly is explained here (last para) in MSDN.
  3. In finalize method, finally block has been put and it calls the Finalize on base class also. This makes sure that all the hierarchy of objects release the resources properly.
    IDisposeable :
  1. As mentioned above, IDispose can only free the resources and can not free the memory consumed by the object itself.
  2. Onus of calling Dispose method on the object still remains with the user. Just implementing IDisposable will not make sure that all resources are released properly. Dispose method will not be called automatically by framework except object is called with “using”.
  3. Calling dispose is not thread-safe.
  4. It is better to consider implementing try..finally block inside the dispose method because if during the execution of dispose method any exception occurs there is no way left to free the resources.

References :


Design Principles

October 1, 2010 16 comments

In this post, I will be trying to describe my understanding about the design principles which is popularly known as “SOLID” principle.

“SOLID” is abbreviation formed by collecting initials of five basic designing principles namely,

  1. Single Responsibility Principle
  2. Open – Closed Principle
  3. Liscov Substitution Principle
  4. Interface Segregation Principle
  5. Dependency Inversion Principle

Let’s try to understand all these principles in brief with some examples :

Single Responsibility Principle :

This principle states that

There should never be more than one reason for class to change.

This principle is simplest however not so simple to apply effectively. Normally while designing the software we are tend to think  in terms of physical grouping and boundaries rather than thinking in terms of responsibility and functionality.

e.g. We have one window in the application which fetches the data from database and displays in the window. Following is the skeleton of the window class :

  public class DisplayWindow
      // establishes connection to database
      public void ConnectDataBase();
      // disconnect connection to database
      public void DisconnectDataBase();
      // gets data from databse
      public void GetData();
      // displays data read from database
      public void DisplayData();

In Above example, all the implementation pertaining to said window has been grouped together in the DisplayWindow class. This  is definitely not following the Single Responsibility Principle. DisplayWindow class in this example is having responsibility of  data retrieval and representation both. There are two problems with this kind of approach :

1. it results in tight coupling between data and representation.

2. All the code has been stuffed in one class only so when changes are made to code it is more prone to regression defects.

If we want to segregate the classes based on the responsibility then it can be done as follow :


So we can make two class namely Window class and DataManger class. Here responsibility of both the classes are very clear. Window class is responsible for displaying data and DataManager is responsible for retrieving data from Database and supplying it to presentation layer. This results in decoupling of data and presentation. Also, such change can make DataManager class reusable.

Hence, when we think about the responsibilities it will result in code which is not so tightly coupled and it will increase the reusability.

Open – Closed Principle

This principle states

Software Entities (Classes, Modules, Functions, etc.) should be open for extension but closed for modifications.

This is very important principle and it states that design the code in such a way so that when the requirement changes, it is possible to meet the requirement by extending the module rather than making changes to existing implementation. It seems like kinda impossible right? However attempt can be made to achieve this objective.

Let’s consider one problem where banking application needs to calculate the interests for various types of account. Following code can meet the requirement :

public class BankApp
      public void CalculateInterest(string accountType)
          switch (accountType)
              case "Savings":
                  // routine to calculate savings account interest
              case "Current":
                  // routine to calculate current account interest

Now bank introduces new account type i.e. “SavingsPlus”. Implementation has to change to calculate the interest for this new account type to accommodate this new requirement. So in above implementation one new case should be added for new account type. This mean altering the existing implementation every time new account type is introduced. Also, when new account type is added, code has to be changed at all places where action needs to be decided based on the account type. The scenario discussed here is very simple but in real world application altering existing code which is working is definitely risky and can cause regression defects.  Also, one requirement triggering changes at multiple places in already running code is also not desirable. Open-Closed principle is exactly meant for such situation.</p> <p>Consider following solution for above problem :</p> <p><a href=”https://csharpsimplified.files.wordpress.com/2010/10/image1.png”><img style=”display:inline;border-width:0;” title=”image” border=”0″ alt=”image” src=”https://csharpsimplified.files.wordpress.com/2010/10/image_thumb1.png&#8221; width=”593″ height=”321″ /></a></p> <p>In above design, Abstraction has been achieved by introducing “Account” base class. Whenever new account type is introduced we can add one more concrete class deriving from “Account” base class and add the interest calculation routine to concrete class. Doing so we don’t have to change the existing implementation at all when new account type is introduced thus making existing code fully closed while code is still extendible.

  public class BankApp
      public void CalculateInterest()
          foreach (Account account in accounts)

Two principles which are key to meet Open-closed principle is Abstraction and Polymorphism. Abstraction helps us in making our code more extensible while polymorphism helps us in making our code close. This is quite apparent from above example.

In real world, no implementation can be 100% closed e.g. if the way interest is calculated is changed then above design is not closed. In order to make change to interest calculation routine we have to change the “CalculateInterest” method of each concrete account classes. However while implementing the calculation routine if some abstraction can be achieved then changes required can be reduced or existing implementation can remain closed when new requirement comes.

Liskov Substitution Principle

This principle state

Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.

This principle stresses on the fact that when sub classing is done, it should not break the base class implementation and subclass – superclass should remain interchangeable. To understand this let’s take following example :

  public class Rectangle
      private double width;
      private double height;

      public Rectangle(double w, double h)
          width = w;
          height = h;

      public virtual void SetHeight(double h)
          height = h;

      public virtual void SetWidth(double w)
          width = w;

      public virtual double GetHeight()
          return height;

      public virtual double GetWidth()
          return width;

  public class Square : Rectangle
      private double size;

      public Square(double s) : base(s,s)
          size = s;

      public override void SetHeight(double h)
          // for square we have to keep both height and width same

      public override void SetWidth(double w)
          // for square we have to keep both height and width same

In above code sample, Class Square is derived from Rectangle. In Square class when SetHeight is called we have to set both height and width in order to keep the sides same for square.

Now consider following use for the above implementation :

  public class EditorApp
      public void ReduceWidthToHalf(Rectangle r)
          r.SetWidth(r.GetWidth() / 2);

      public static void main(string[] args)
          EditorApp editor = new EditorApp();

          Square sq = new Square(20);

          // calling this will result in reduction of both width and height by half.
          // This is not desirable as per implementation of ReducteWidthToHalf method.
          // When actual object passed is Rectangle only width is reduced to half but
          // when Square object is passed, it reduces both height and width by half.

          // this mean both base class and sub class objects exhibit different behaviors
          // and they are not interchangable without breaking functionalities.

In above code sample, as my code comment mentions base class and derived class exhibits different behavior and Square can not be substituted for a Rectangle and vice versa.

So in nutshell, Liskov principle states that never break the base class implementation while subclassing.

Interface Segregation Principle

This principle states

Clients should not be forced to depend upon interfaces that they don’t use.

This principle basically talks about the problem of “Polluted”/”Fat” interfaces. Following example (from objectmentor)should clarify what is Fat interface :

There is a door system with normal door operation like door open, close and getting the door status, etc. This is a normal door operation. Basic IDoor interface below should do the needed for this :



However, some specialized door system is requested where door should close / alert user about it being open after certain time period. So this additional feature will require to add some timer function to existing door system as shown in right :

Well, Changing the IDoor interface have it’s implications :

1. Adding new method to existing interface will break the existing implementation because all the classes that derive from the IDoor interface will have to implement newly added method “TimerFunction”.

2. Though not all doors need a timer function, still as per new interface design all the objects that derive from IDoors will have to implement TimerFunction which is not desirable.

Also, adding new features in this way will make interface more n more fat and it will lead to tightly coupled code. Also, making interface fat will result in violation of Open-Close principle.

So solution to this problem is to segregate the Interfaces. Ideal way is to design the separate interface for each client.


So now we have two interfaces as shown in the figure. So to construct simple door we use IDoor interface while constructing TimedDoor we use both IDoor and ITimeFunction interface. In such design, the abstraction has been achieved in IDoor while add-ons have been segregated to new interface. Also, with this design even if changes in ITimeFunction is required than also changes will remain limited only to TimedDoor objects and SimpleDoor objects will remain unaffected. This way the tight coupling which existed in previously design is reduced. Also, after segregation classes are also complying to single responsibility principle.

Dependency Inversion Principle

This principle state

A. High level modules should not depend on low level module. Both should depend on abstraction. Both should depend on Abstraction.

B. Abstraction should not depend on details. Details should depend on Abstraction.

To understand this, consider following Salary Calculator application example where perks for the employee is to be calculated :


Worker is entitled to have various perks. Details of the allowed perk is available inside the Worker class. So in this implementation “ComputePerks” method will iterate through all the perks and go through the if loops to compute the final perk for each employee. But perks entitlement and perks may keep changing i.e. after a while no TransportationPerk is given or new perk say FoodAllownce is added then in this case we will have to change the if loops inside the method to accommodate new structure and this exercise will  repeat every time when perks change. So drawback of this design is :

1. High level module i.e. SalaryCalculator is dependent on the low level classes i.e. various perk calculator classes.

2. Tight coupling exist between the high and low level module.

3. Also, every time low level module changes, High level module has to change which also violates the “Open-Closed” principle.

So to fix this situation we have to follow what this principle is saying i.e. both High and low level module should depend on Abstraction. We should introduce Abstraction layer which can isolate high and low level modules and both can depend on this Abstraction layer. So consider the following new design :


In this design, IPerks interface has been added and now all perks will implement this interface and worker class will use the IPerks. Also, SalaryCalculator class will use the IPerks collection inside the worker class and will calculate the perks by iterating through the list as mentioned in the comment in above diagram. Using this approach,

1. High level SalaryCalculator class is not directly depending upon the Perk classes.

2. Both High and low level classes now depend on the abstraction of IPerks interfaces.

3. Changes in the perk structures i.e. addition or removal of perks will not affect the SalaryCalculator top level class. Every time when perk structure changes only the list inside the worker class will change. So this will also follow the “Open-Close” principle.

So finally, I am done with describing the SOLID principle in brief as per my understanding.  All the principles are very extensive in nature and deserves separate post for each but here it is my humble effort to put them in shortest possible way.  However, people are always welcome to provide their feedbacks/suggestions or pointing out any errors in constructive way.

References :

1. wiki

2. WWW.ObjectMentor.com

3. some other web contents

UpdateSourceTrigger – DataBinding

August 22, 2009 6 comments

Last week while working on two way binding, I discovered one very important settings for binding i.e. “UpdateSourceTrigger”. Before discovering this feature I faced problem in setting the value from target to source. Let me describe the problem I faced.

In my setup, I had no. of text boxes in window whose text property were bound to the property of object in collection. So in this case, source for me was property of the object in collection and target was the text property of textboxes.

I configured my binding object as below :

            Binding binding = new Binding();
            binding.Source = <source object from collection>;
            binding.Path = new PropertyPath
            binding.Mode = BindingMode.TwoWay;
            txtbox.SetBinding(TextBox.TextProperty, binding);

With above binding configuration, source –> target binding worked perfectly for me. But binding from target –> source (i.e. from text box to object’s property in collection) was not working for me. One thing which is important to mention here is, I was changing the text box’s text value in procedural code and not by entering the value in textbox.

It was beyond my understanding why binding was not working? I spent almost half a day trying to figure out this. I googled it but google disappointed me. So I took Adam Nathan’s “WPF Unleashed” book in my hand and started looking for some solution. Again this book came to my rescue. While going through the “Data Binding” chapter in this book, I learned about “UpdateSourceTrigger’ property of the binding object.

“UpdatesourceTrigger” property is very important in “TwoWayBinding” and “OneWayToSource” binding modes. It defines how and when source should get updated.

Value of UpdateSourceTrigger could be any of the value from UpdateSourceTrigger Enumeration. Enumeration values are

  1. PropertyChanged – The source is updated whenever the target property value
  2. LostFocus – The source is updated when target property changes and target object looses focus.
  3. Explicit – The source is updated when explicit call is made to update using “BindingExpression.UpdateSource”.

Target controls have default values set for “UpdateSourceTrigger” for binding object. For text box control, default setting for this property is “LostFocus”. In my case, I was updating the textbox (i.e. target) through code and because of that textbox was not loosing focus. Hence my binding was not working. Then I changed above binding configuration to set the UpdateSourceTrigger property of binding object as following :

            Binding binding = new Binding();
            binding.Source = writeItemInfoList[index];
            binding.Path = new PropertyPath("ItemValue");
            binding.Mode = BindingMode.TwoWay;
            binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            txtbox.SetBinding(TextBox.TextProperty, binding);

And Binding from Target to source started working for me.


May 1, 2009 1 comment

I was looking to copy some bulk data from one of the data table in memory to my SQL DB table. I tried using DBAdapter.Update but it didn’t work as in my source datatable none of the row was in updated/new stage. Then after searching a lot, I found “SQLBulkCopy”.

The SqlBulkCopy class can be used to write bulk data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a DataTable instance or read with a IDataReader instance. To copy the source data to destination table in the sql server, need to set destination table name and execute “WriteToServer” method. Following code snippet

// create sqlBulkCopy object
SqlBulkCopy bulkCopy = new SqlBulkCopy(connString);

// set destination table name for sqlBulkcopy object
bulkCopy.DestinationTableName = "[Table Name]";

// write source data to destination sql table

Performancewise using SQLBulkCopy is far better than using normal Insert/Update commands.

Categories: c#, SQL Tags: , ,