Category Archives: .NET (C#)

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.

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.

DataGridViewComboBoxColumn requires multiple clicks to select an item

If you have ever used a DataGridView with a DataGridViewComboBox column, then you would have definitely noticed that you need multiple clicks to select an item in the combo box. This is very annoying because every time you want to select a different item from the combo box, you need at least 2-3 clicks.

Fix

Fortunately, there is a simple fix for this: set the EditMode property of the data grid view to EditOnEnter. So, when the user enters the control, the cell is automatically put in edit mode, so when you actually click on the combo box, you can see the drop down list.
A bug

That being said, there is a bug associated with this. With the EditMode property set to EditOnEnter, when you select a row by clicking on the row header, the entire row is selected, but one cell will be in edit mode. What this means is if you try to delete the row by selecting the row header, you cannot delete the row because the delete key is actually being sent to the cell being edited and not the row.

This page has more details on this bug and also a workaround.

Datagridview: Get SelectedIndex of DataGridViewComboBoxColumn

This seems to be a straight forward thing, but Microsoft only knows why this simple feature is not supported in DataGridView.

If you have a ComboBoxColumn in your DataGridView and you want to know what is the selected index of the combo box, then you need to do this:

1. Handle the EditingControlShowing event of DataGridView. In this event handler, check if the current column is of our interest. Then we create a temporary ComboBox object and get the selected index:


private void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 0)
{
// Check box column
ComboBox comboBox = e.Control as ComboBox;
comboBox.SelectedIndexChanged += new EventHandler(comboBox_SelectedIndexChanged);
}
}

void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedIndex = ((ComboBox)sender).SelectedIndex;
MessageBox.Show("Selected Index = " + selectedIndex);
}

A rather round-about solution where a simple one would have sufficed.

Right click on TreeView: Get the node clicked at

Problem:

There is a TreeView control with n number of nodes. When the user right clicks on the TreeView control, get the node on which the right click was performed.

Background:

In TreeView control, SelectedNode property is set whenever left click occurs. This is not true for right clicks. So, we need to have some workaround for this.

Solution 1:

The most popular solution is to handle the MouseDown event. Check if the click was a right click and then use the TreeView control’s GetNodeAt API to get the node which was clicked at.

private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
TreeNode selectedNode = treeView1.GetNodeAt(e.X, e.Y);
MessageBox.Show("You clicked on node: " + selectedNode.Text);
}
}


Solution 2:

Handle the NodeMouseClick event. The TreeNodeMouseClickEventArgs has the node which was clicked at.

private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
MessageBox.Show("You clicked on node: " + e.Node.Text, "Solution 2");
}
}

SelectedNode property of a treeview is set whenever a left click occurs. Why can’t the same be applied for right click? Right click on a treeview is such a common UI event, that users will benefit from it.

Removing items in a list while iterating through it

See the following code:

List list = new List();

for (int i = 1; i < 10; i++) { list.Add(i); } foreach (int i in list) { list.Remove(i); } [/source] Do you see anything wrong in this piece of code? No? Okay. Execute this code and you will get a System.InvalidOperationException with the message “Collection was modified; enumeration operation may not execute.”

The first time foreach loop executes, it deletes the first item and in the second iteration, this nasty exception is thrown. Reason? You deleted the first item and the list has changed. If not for the InvalidOperationException , you could have got a IndexOutOfRange exception while traversing the list.

So, how does one delete some items in the list while iterating through the list? I faced this problem in my project today and I couldn’t come up with an elegant solution. I did come up with a hack. I identify all items that need to be deleted and mark them with a flag (I need one iteration here). In another iteration, I create a new list and copy all those items which are not marked.

Sorry, I couldn’t come up with something better. If you have a solution or a better fix, please do let me know. Please note that if I want to remove all items, I can use list.Clear(). I am talking about a scenario where I want to delete only a select few items.

Update:

I read somewhere that if you use for loop instead of foreach, this problem does not arise. True, you will not get an exception, but you might not delete the items that you actually want to delete. Let’s see what happens in our case.

List list = new List();

for (int i = 1; i < 10; i++) { list.Add(i); } for (int i = 0; i < list.Count; i++) { int remove = list[i]; list.Remove(remove); } [/source] You will delete items 1, 3, 5, 7 and 9. After the for loop exits, your list will still have 2, 4, 6 and 8. Surprised? Let's see why this is so. First iteration: i = 0, remove = 1. Deleted item = 1 Once you delete this item, the list has changed. So, the first element in the list is now 2.
Second iteration: i = 1, remove = 3. Deleted item = 3
Third iteration: i = 2, remove = 5. Deleted item = 5

and so on….

So, replacing foreach with a for is not a solution.