Javascript: Limiting string length in textbox

I am wetting my beak in the Javascript world and I learn something new every day. When I faced this problem of limiting the length of string that the user can enter in a textbox, Google failed to return a satisfying result. My co-worker told me about the amazing attribute maxLength that is available for textbox. Works like magic.

If you want to restrict the length to 50, then just add an attribute ‘maxLength’ like this:

<input id="myTextBox" type="text" name="myTB" maxLength=50>

If you want to do this in javascript using jquery, then you need to add this line in your js file:

$("#myTextBox").attr("maxLength", 50);

I wonder why Silvelright textbox does not have something similar. This is a very helpful attribute for developers, do you agree?

Silverlight 4 XAML Parsing Error

If you are using Silverlight 4, chances are you have encountered the nasty exception while parsing a XAML file, something on the lines of : “Parser internal error: Object writer ‘xClassCanOnlyBeUsedOnLoadComponent’”. It can be quite frustrating to debug this because you can’t step into the Load method and the line number details that the exception provides is basically useless.

Whenever you see the term xClassCanOnlyBeUsedOnLoadComponent, look for x:Class in your XAML file. Check whether the namespace specified is correct and your code behind (xaml.cs) also uses the same namespace. If you are using a XAML file only without a code behind file (xaml.cs), then you do not need the x:Class tag in your XAML file. Remove this and the exception should go away.

Let me know if this solves the problem. That being said, Microsoft should really work on improving its exceptions. The least they could do is provide accurate information.

Forcing binding update in TextBox

A typical usage of TextBox control in Silverlight is to bind it to a property and set the bind as two way. When the property changes, the TextBox is updated with the change and if the user changes the text in the TextBox, it is saved back to the property. Something like this:


<TextBox Text="{Binding Path=State, Mode=TwoWay}" />

A common problem developers face is when you have a TextBox control and a Submit button, which is enabled only when the data in TextBox is modified. The Submit button is not enabled until the LostFocus event of text box is fired. And LostFocus won’t be fired unless you click on something else. In this case, we can force the text to be updated. Register for TextChanged event and in this event handler, get the binding object and force an update.

 


<TextBox Text="{Binding Path=State, Mode=TwoWay}" TextChanged="textBox_TextChanged"/>

void textBox_TextChanged(object sender, TextChangedEventArgs e)
{

if(sender is TextBox)
{
TextBox tb = sender as TextBox;
BindingExpression binding = tb.GetBindingExpression(TextBox.TextProperty);
if (binding != null)
{
binding.UpdateSource();
}
}

}

Ta-da!

SelectionChangedEvent in RadGridView

If you have used RadGridView with a GridViewComboBoxColumn, you know it does not support SelectionChangedEvent directly. There are many scenarios where you want to handle some validation or perform some action when the user selects an item in a combo box but the absense of SelectionChangedEvent for GridViewComboBoxColumn makes this really hard. Good news is, there is a solution. Here it is, see if it helps.

Let’s say you have a RadGridView defined like this:


<telerik:RadGridView x:Name="myGridView">
 <telerik:RadGridView.Columns>
 <telerik:GridViewComboBoxColumn Header="Page" UniqueName="column1"  />
 </telerik:RadGridView.Columns>
</telerik:RadGridView>

 
In your code behind, preferably in the Loaded event, add this code:


this.AddHandler(RadComboBox.SelectionChangedEvent,
new Telerik.Windows.Controls.SelectionChangedEventHandler(ComboBox_SelectionChanged));

Add an event for Selection changed event. The name of your method and the event above should match.


 void ComboBox_SelectionChanged(object sender, RadRoutedEventArgs args)
 {
RadComboBox comboBox = (RadComboBox)args.OriginalSource;

if (comboBox.SelectedValue == null)
return;

// Get the current cell
GridViewCell cell = myGridView.CurrentCell;

// Handle the situation where a cell is null. It can be when you are adding a new row
if (cell == null)
{
return;
}

GridViewRowItem row = cell.ParentRow;
GridViewColumn col = cell.Column;

// This if block here is to handle only the combo box column desired. You can
// have multiple combobox columns and this event will be triggered for all of them.
// Handle what is required and ignore the rest
if (col.UniqueName != "column1") // Unique name that you specified in the XAML
{
return;
}

// YourDataObject is whatever data object you are using
YourDataObject item = comboBox.DataContext as YourDataObject;

//SelectedItem returns object. Convert it to whatever your binding object type is
object selectedItem = comboBox.SelectedItem;

// Now that you have your selected item, you can do whatever you want.
// In case you want to disable other cells on this row, just use row.Cells property.
}

That’s it. You are all set now.

Some points to note:
1. SelectionChanged event will be triggered for all combo box columns and combo boxes you have. You need to find out if the deisred combo box column is changed.
2. This event is triggered not only after the selection is changed, but also when the user just clicks on the combo box. There is a solution to handle this, but that’s another story altogether.
3. This was tried with VS 2010 and Silverlight 4.

Virtual PC: Switching between virtual pc and host pc

Once you start using your virtual PC, how do you get control back to the host PC? The help document of VPC says to press the host key, but what on earth is the host key? It’s the right ALT key of your keyboard. Not any ALT key, but the RIGHT ALT key. Press it and the mouse control comes back to your host PC.

You can launch your virtual PC in full screen mode. Once you have done that, how do you quit full screen mode? Again, press host key and enter. That is RIGHT ALT + Enter.

Simple, yet it took me some time to figure it out.

Regular expression for a line with only white spaces

I had this requirement to check whether the input string contains only white spaces. I am not a regular RegEx user, so it took me some time to achieve this.

^[ \t\r\n]*$

That’s it. The meaning of the above pattern is [Beginning of line] [0 or multiple white spaces] [End of line]. Note that this pattern matches an empty string also, since we have given * after white spaces. If you want to strictly look for white spaces and exclude empty strings, then change the * to +.

This is not such a big deal that it requires a blog post of its own, but I didn’t find this information when I looked for it. So putting this out there for anyone who comes looking for it.

Review: Introduction to Silverlight 3 by Laurence Moroney

The book intends to give an overview of the features in Silverlight 3. It starts with very basic things like creating a Hello world project in Silverlight 3, the different elements in SL3 project and hand coding all those elements outside the Visual Studio environment. Later on, the book dives into advanced-beginner topics like writing XAML code, using Expression Blend etc.

The book touches on different topics at a superficial level and doesn’t give deep insight into any of the topics. This is what is expected from an ‘Introduction’ book, so the purpose is served. There is a detailed section (couple of chapters) on UI controls available in SL3. It introduces basic controls like Button, Text Block, Label and moves on to slightly advanced controls like DataGrid, ScrollViewer etc. The author explains designing UI using XAML. This is a must for anyone who don’t have Blend. Learning XAML is the biggest challenge in XAML, in my opinion.

There is a small section on MVVM where the author discusses two-way data binding. I was hoping this section would be a bit deeper, but I guess that was not in the scope of this book.

The intention of the book is not to showcase the differences in SL3 and the previous versions of Silverlight. It isolates SL3 and focuses only on this version. For someone who is starting to learn Silvelright and chooses SL3 as the version, then this book is ideal to start with. The reader need not worry about the compatibility issues with older versions unnecessarily.

If you are looking for a quick familiarity to Silverlight 3, then this is the book for you.

Tagged , , ,

Hyperlink or Linklabel in Silverlight

Silverlight 3 does not have a control similar to link label. This post tells you how you can add a hyperlink or linklabel in Silverlight 3.

Expression Blend:

1. Create a Silverlight project.

2. Add a Text Block object. Change the text to suit your requirement, let’s say My Website.

3. Under Properties->Brush tab, change the color to R=0, G=0, B=204.

4. Under Properties->Text tab, click on the Underline button. This will add underline to the text.

5. Under Properties->Common Properties, change the Cursor to Hand. (Choose from the drop down list)

6. Under Events tab, double click on MouseLeftButtonUp to add a event handler. In the code-behind, you can open the desired website.

Modifying XAML:

1. Create a Silverlight project

2. In MainPage.xaml, add the following lines

<TextBlock Text="My Website" TextWrapping="Wrap" TextDecorations="Underline" Foreground="#FF0000CC" Cursor="Hand" MouseLeftButtonUp="TextBlock_MouseLeftButtonUp"/>

In the event handler, add the code to open your website.

Tagged , , , , , ,

Calling a Javascript function from Silverlight

This article talks about how you can call a javascript function from Silverlight.

1. Create a Silverlight project of type ‘Silverlight Application’ in Visual Studio. You will get a dialog box asking you whether you want to host your application on a website. Check this checkbox and click on OK.

2. Open MainPage.xaml and replace the existing content with this:

<UserControl x:Class="Blog1.MainPage"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
 <Grid x:Name="LayoutRoot">

 <Button x:Name="testButton" Content="Call js function" Click="testButton_Click"
 Width="150" Height="40" />

 </Grid>
</UserControl>

3. In MainPage.xaml.cs, a method testButton_Click should have been created. Replace the method with the one below. If the method is not present already, add it yourself.

 private void testButton_Click(object sender, RoutedEventArgs e)
 {
 HtmlPage.Window.CreateInstance("calledFromSilverlight", new string[] { "Silverlight User" });
 }

4. Save all the files and build your solution.

5. Go to the Bin folder where the xap file is located. Normally under <project>/Bin/Debug. There should be a file named TestPage.html. Open this file in your Visual Studio and add the following function.

 function calledFromSilverlight(user) {
 alert("Hello " + user);
 }

6. Open this page in a browser. You should see a button with text ‘Call js function’. Click on this and if everything is fine, you should see a pop-up window saying ‘Hello Silverlight User’.

That’s it. You just invoked a javascript function from Silverlight. Wasn’t that easy?

Note:

  1. If you rebuild the solution, the TestPage.html is created again, removing all the changes that you have made. You can make a copy of this file, name it MyTestPage.html and add the javascript function in this.
  2. This works for Silverlight 3 and Visual Studio 2008.

Next up: Calling Silverlight method from Javascript.

Firefox 3.5: Firefox exits when you close the tab

There is a serious problem with Firefox 3.5. When you have only one tab open in Firefox and when you close that tab, instead of opening a new, blank tab, Firefox itself exits. This is annoying because you would expect a new tab to open, but you see Firefox disappear in front of you and your heart sinks.

Turns out there is an easy fix for this.

1. Open Firefox and type about:config in the browser address bar. You will get a warning, acknowledge it and carry on.

2. In the filter, type browser.tabs, you will see some entries in the table. You will also see ‘browser.tabs.closeWindowWithLastTab’.  Its value should be true. Right click on this and click on Toggle. The value should change to false.

3. Close the browser and open again.

4. Verify that the browser doesn’t close when you close the only open tab.

Tada!

Tagged ,
Follow

Get every new post delivered to your Inbox.