Category Archives: Silverlight 3

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.

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.