Silverlight 4.0: Applying TextChange behavior to the TextBox

Posted by: Mahesh Sabnis , on 7/17/2011, in Category Silverlight 2, 3, 4 and 5
Views: 75919
Abstract: This article demonstrated how to define a custom behavior and extend the functionality of the Silverlight controls like the TextBox

I was asked a question recently about updating the binding source property during the TextChanged event, for the textbox. All those who are using Silverlight may be aware that when the source property is bound with the Textbox’s Text property, then to update the source property value, we must use the LostFocus event on the TextBox. However if you need to make it possible during the TextChanged event, then you need to define custom interactive behavior for the TextBox.

To attach a custom behavior to the TextBox, we need to add a reference to the System.Windows.Interactivity.dll file in our Silverlight project. This is available in Microsoft SDK’s Expression folder as below path:

c:\Program Files (x86)\Microsoft SDKs\Expression\Blend\Silverlight\v4.0\Libraries\System.Windows.Interactivity.dll

This dll provides various classes for element behavior, which can be customized for control specific event. One of the classes we are using in this article is the Behavior class. This class encapsulates state information and ICommands into the attachable object and performs some action when the control raises a specific event. E.g. If we attach a behavior with the TextBox and its TextChanged event, then during the execution when the end-user enters any text in the TextBox, the behavior associated with the TextChanged event will be automatically executed. Let us see some code:

Step 1: Open VS 2010 and create a new Silverlight project. Name the project as ‘SL4_TextBox_Interactivity_Behavior’. In this project, add a reference to ‘System.Windows.Interactivity’ dll.

Step 2: In the project, add a new class file and name it as ‘Data_Behavior_Classes.cs’. This file will contain the TextBox behavior class and data source classes as below:

silverlight-textchanged-behavior

The above class defines the behavior for the TextBox element. The generic class Behavior<T> is currently typed to the textbox. The AssociatedObject represents the object to which the behavior is to be attached. Currently it attaches the TextChange event for the TextBox.

Step 3: In the same class file added above, add following two classes which act as a Data Source:

silverlight-data-behavior

silverlight-data-behavior1

The EmployeeCollection class defines Employees as an ObservableCollection<T> object which is initialized to some Employee records using the constructor. This is used to bind Employee data to the DataGrid. The public property EmpName will be used to filter Employees from the Employees property. It defines some complex logic to run an Employee filter. I have added comments in the code so please read it carefully. I have declared a temporary ObservableCollection<Employee> property of the name EmployeedFiltered, which will be used to store Employees data during the TextChanged event filtration. In a real scenario, if you use WCF Service to fetch data, then the logic will be much easier.

Step 4: Open MainPage.Xaml and define System.Windows.Interactivity and the current application’s namespace as below:

image

Step 5: Drag-Drop the DataGrid and define columns in it binding to the public properties of the Employee class created above. The xaml code will be as shown below:

silverlight-datagrid

If you observe the XAML above, the TextBox txtEmpName is set to the behavior as shown here:

image

The above lines implies that when the TextBox object is drawn on the UI, the behavior with TextChange event will be associated with it. So now when the user enters any text in the TextBox, the TextChange event will be fired and the Binding property ‘EmpName’ will be updated.

Step 6: Run the application and the result will be as below:

clip_image002

Now enter some text in the TextBox and the Result will be as shown below:

clip_image004

Conclusion: By defining a custom behavior, we can extend the functionality behavior of the Silverlight Element system.

The entire source code of this article can be downloaded over here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce the The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this eBook aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on .NET Standard and the upcoming C# 8.0 too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Niranjan poddar on Thursday, February 16, 2012 5:04 AM
Thanks a lot for your article.
Comment posted by jamal ali khan on Thursday, May 17, 2012 1:02 AM
Guys here is a comprehensive Filters class open source for you.

http://jklogic.blogspot.com/2012/05/silverlight-textbox-filters.html
Comment posted by Trina Maxwell on Friday, May 3, 2013 10:37 AM
I would love to use this if it will help with the program I have. It is currently working, however, when you input numbers in the textBox and then try to insert the decimal (price) it moves the cursor to the front of the numbers and will not allow you to enter the decimal untill all your numbers are entered and then you have to arrow back to place the decimal where it belongs. My code is as follows that I am using for the textBox:
private void textBox2_TextChanged(object sender, TextChangedEventArgs e)
        {
            
            //Adding ToolTip
            ToolTipService.SetToolTip(textBox2, "Enter Price, numbers first, then arrow back to add decimal.");
            
            if (Double.TryParse(textBox2.Text, out value2))
            {
                textBox2.Text = value2.ToString();
            }
            if (textBox2.Text == null || textBox2.Text == "") value2 = 0;
            {
                textBox2.Text = value2.ToString();


            }

            if (textBox2.Text.EndsWith(".97") == true)
            {
                value21 = 0; value37 = 0; value70 = 0;
                textBox21.Text = value21.ToString();
                textBox37.Text = value37.ToString();
                textBox70.Text = value70.ToString();
            }

            if (textBox2.Text.EndsWith("1") || textBox2.Text.EndsWith("2") || textBox2.Text.EndsWith("3") || textBox2.Text.EndsWith("4") || textBox2.Text.EndsWith("5") || textBox2.Text.EndsWith("6") || textBox2.Text.EndsWith("8") || textBox2.Text.EndsWith("9") || textBox2.Text.EndsWith("0") == true && (value2 < 100.00))
            {
                value70 = 1;
                textBox70.Text = value70.ToString();
            }
            if (value2 > 100.01 && value2 < 149.99)
            {
                value70 = 2;

                textBox70.Text = value70.ToString();
            }
            if (value2 > 149.99)
            {
                value70 = 3;
                textBox70.Text = value70.ToString();

            }
        }


If you know how I can make this work to allow the proper input of the price from enduser standpoint please help! Thanks

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook