While working on solutions in Visual Studio, it is often the case that you have many projects contained within the solution. Even on fast machines, Visual Studio performance can start to drag when you begin working on the solution. In my past experience, I have found that I typically work on only a few projects at a time. I found that unloading the unnecessary projects can help to conserve memory. So how do you unload a project from a solution in Visual Studio? Simple, just right-click on the project name and click Unload Project.

The unloaded projects will appear grayed out along with the text (unavailable).

This trick also works well if your code is under source control. As far as I can tell, the unload/load state of any given project is stored in the corresponding *.SUO file for a solution so this change won’t be tracked by your source control client.
If you are a ReSharper user (and you should be), you know that ReSharper can consume lots of memory while indexing the various symbols. When you unload a project, ReSharper will ignore files from these projects. I also find this particularly useful because files with similar names will no longer show up in your quick search lists.
This tip is fairly trivial, but I have never once seen someone do this in practice. I hope this helps!
Time is almost up on the 2009 Silverlight Control Builder Contest! So far, we have received 8 entries. Yes, we have a real contest this year. If you are planning on entering the contest, make sure you have submitted your entries before 9/19/2009 at 12:00 AM EDT.
This topic has plagued me for some time now and I finally was able to engineer a working solution to achieve my goal. The challenge was to be able to display a series of items each containing a header and an variable number of child items. By itself, this is a fairly trivial problem to overcome, however, I had a few additional constraints that change the nature of the problem completely.
Constraint #1: Instead of scrolling, the layout must display whatever possible in the available height, and the remaining items should appear on subsequent pages.
Constraint #2: Each item will consist of a header and a variable number of sub items. If there is no remaining space to display sub items on the current page, the items should appear on the next page, along with the appropriate header.
Constraint #3: If the available screen height changes, the layout should adjust to display as many items and sub items as possible.
Constraint #4: If there is no room to show any sub items after displaying the header on the current page, then don’t display the header at all.
The illustration below should help you visualize how the paging should work:
Trials and Dead-Ends
Has this path been travelled? It is likely that someone else has indeed run into the same problem and blogged their experiences, so I search and discover something close, a Paging Wrap Panel in WPF. This example is very similar to my requirements, only it assumes that all items are the same height. In my scenario, the items (including sub items) are variable height and I need to repeat headers when all of the sub items don’t fit on a page. Cue the Sad Trombone.
What does the StackOverflow crowd think? I posted a question and got a few responses, but nothing like I had hoped.
Originally, I had planned to iteratively add an item and check the height after each item. If the item did not fit in the available space, I would suspend rendering items until the layout was moved to the next page. My main issue was that I could not determine the height of an item until after it had been rendered.
After many failed attempts, I was starting to lose hope, but I eventually discovered that I could add all of the items in one iteration and then cycle back through and hide items until the appropriate set was being displayed (with respect to the current page).
So, I’ve included a live demo that you can try out and the source code is available as well. This isn’t my final version of the code. I ended up refactoring, generalizing, and re-packaging this as a reusable control for my own uses. I don’t plan on releasing the final version, but this should get you started if you have the same problem. Enjoy!
Download Source Code
Live Demo

With all of the new features introduced in Silverlight 3, it’s easy to see how some features get very little coverage (or no coverage at all). The ItemContainerGenerator is one of those features. When building controls based upon the ItemsControl, there are many cases when you need to obtain the container for a particular item. To perform this task in Silverlight 2, you had to develop your own crude implementation of the ItemContainerGenerator. Fortunately for us, the ItemContainerGenerator is now baked right in!
The ItemContainerGenerator for a particular ItemsControl is exposed by the ItemContainerGenerator property:
The Silverlight Toolkit team built their own version of the ItemContainerGenerator (located in ItemContainerGenerator.cs in SL2 Source) to support the TreeView control. However, in the recent Silverlight 3 release, this class has been removed and the TreeView control has been updated to take advantage of the built-in version.
Right on the heels of the Silverlight 3 announcement, the 2009 Silverlight Control Builder Contest was just announced. The concept is simple, build a control using Silverlight and submit it to the site. The top 3 entries will win some really cool prizes!
Based on feedback gathered from last year, the contest is much improved:
- The contest is world-wide this time!
- Extended contest duration. This year, the contest lasts until September 19th, 2009 at 12 AM EDT.
- Silverlight 3 entries are accepted (of course!)
- Contest entries will be published shortly after they are submitted.
So spread the word! I can’t wait to see what the Silverlight community can do!
By the way, follow @SLContest on Twitter for updates. I am hoping to add more prizes soon!
I noticed the other day that Storyboard has a SetTarget method, but it does not have a corresponding GetTarget method. So how can you find the target of a Timeline child? Fortunately, Storybard has a GetTargetName method, we can use this method to obtain the name of the target and then search parent container’s children for a matching child. Suppose we had the following code:
<Grid x:Name="LayoutRoot">
<Grid.Resources>
<Storyboard x:Key="FadeOut">
<DoubleAnimation
To="0"
Duration="0:0:3"
Storyboard.TargetName="TestText"
Storyboard.TargetProperty="(UIElement.Opacity)" />
</Storyboard>
</Grid.Resources>
<TextBlock x:Name="TestText" Text="The Rain In Spain"></TextBlock>
</Grid>
In the example above, the TextBlock TestText is the target of the DoubleAnimation timeline in the FadeOut Storyboard. We can find this using the following code:
var fadeOut = (Storyboard)LayoutRoot.Resources["FadeOut"];
var doubleAnimation = (DoubleAnimation)fadeOut.Children[0];
var targetName = Storyboard.GetTargetName(doubleAnimation);
var target = LayoutRoot.Children.Single(c => ((FrameworkElement)c).Name == targetName);
It is worth noting that you must specify a TargetName, or the GetTargetName method will return null. In other words, if you are creating a Storyboard programmatically, and you only use the SetTarget method instead of the SetTargetName method, the GetTargetName method will not return what you expect:
var sb = new Storyboard();
var da = new DoubleAnimation();
da.To = 0;
da.Duration = TimeSpan.FromSeconds(3);
Storyboard.SetTarget(da, TestText); // Instead try: Storyboard.SetTargetName(da, "TestText");
Storyboard.SetTargetProperty(da, new PropertyPath("(UIElement.Opacity)"));
sb.Children.Add(da);
var target = Storyboard.GetTargetName(da); // Returns null if we don’t call SetTargetName
Enjoy!
In many situations, it is important that your Silverlight appilcations load as quickly as possible. For example, when building a Silverlight Advertisement, the user should not experience a significant load time. The advertisement should load just as fast as the other page assets. But how do you achieve this when your application includes heavy-weight resources, such as video or images? Of course you could pull these individual assets from a server during runtime, but if your assets are packaged inside the XAP package, you need a better solution.
The most common solution I have seen is to build a small, light-weight Silverlight application that will behave as a preloader for the main application. The preloader application will load first to provide some immediate feedback to the user and then begin downloading the main application asynchronously in the background. As soon as the main application has finished downloading, the preloader application will instantiate and then inject the main application into its visual tree.
It is important that the preloader application is as small as possible. However, most of the preloaders I have seen take advantage of LINQ to parse the AppManifest.xaml file. LINQ is great, but this requires you to reference System.Xml.Linq.dll in your application. Uncompressed, this assembly is 118KB. If you want to minimize your XAP size, you need to eliminate this dependency. Below, I have written a small preloader that uses the good old-fashioned XmlReader to parse the AppManifest file. To take advantage of this preloader, simply include this class in your preloader application and call it using the example code below:
XapLoader
public class XapLoader
{
public event EventHandler<XapLoaderEventArgs> XapLoaded;
private string m_rootAssembly;
private string m_typeName;
public void LoadXap(Uri xapUri, string typeName)
{
m_rootAssembly = Path.GetFileNameWithoutExtension(xapUri.ToString());
m_typeName = typeName;
WebClient wc = new WebClient();
wc.OpenReadCompleted += wc_OpenReadCompleted;
wc.OpenReadAsync(xapUri);
}
private void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
var manifestStream = Application.GetResourceStream(
new StreamResourceInfo(e.Result, null),
new Uri("AppManifest.xaml", UriKind.Relative));
string appManifest = new StreamReader(manifestStream.Stream).ReadToEnd();
string assemblyName = m_rootAssembly + ".dll";
XmlReader reader = XmlReader.Create(new StringReader(appManifest));
Assembly asm = null;
while (reader.Read())
{
if (reader.IsStartElement("AssemblyPart"))
{
reader.MoveToAttribute("Source");
reader.ReadAttributeValue();
if (reader.Value == assemblyName)
{
var assemblyStream = new StreamResourceInfo(e.Result, "application/binary");
var si = Application.GetResourceStream(assemblyStream, new Uri(reader.Value, UriKind.Relative));
AssemblyPart p = new AssemblyPart();
asm = p.Load(si.Stream);
break;
}
}
}
if (asm == null)
throw new InvalidOperationException("Could not find specified assembly.");
var o = asm.CreateInstance(m_typeName);
if (o == null)
throw new InvalidOperationException("Could not create instance of requested type.");
RaiseXapLoadedEvent(o);
}
private void RaiseXapLoadedEvent(object instance)
{
if (XapLoaded != null)
{
XapLoaded(this, new XapLoaderEventArgs(instance));
}
}
}
public class XapLoaderEventArgs : EventArgs
{
public object Instance { get; set; }
public XapLoaderEventArgs(object instance)
{
this.Instance = instance;
}
}
// USAGE
...
XapLoader loader = new XapLoader();
loader.XapLoaded += loader_XapLoaded;
loader.LoadXap(new Uri("MyTestApp.xap", UriKind.Relative), "MyTestApp.Page");
...
...
private void loader_XapLoaded(object sender, XapLoaderEventArgs e)
{
var instance = e.Instance as UIElement;
if(instance != null)
{
LayoutRoot.Children.Add(instance);
}
}
There are probably more optimizations that would shrink the size down even further. If you can find any significant optimizations, please let me know and I’ll update the code. I’ve attached a sample project below. Enjoy!
In my spare time, I have been re-writing the Star Selector control that is part of Silverlight Contrib. I re-wrote this control because there were several things I wanted to accomplish. This re-write includes quite a few new features. I will highlight them in the next few sections:
Half-Star Selection
The control supports enabling half-star selection. To enable or disable this feature, simply set the AllowHalfStarSelection property accordingly. The default value is false.
DisplayValue and Value Property Data Types
The DisplayValue and Value properties have been changed from an Integer to a double data type. This allows you to select half-stars and the control will reflect the specified value by rounding up or down to the nearest half-star when AllowHalfStarSelection is true.
DisplayValue reflects which stars will be visible. Value reflects what the user has chosen. I have split this concept into 2 properties to allow for more flexibility when using the control.
For example, suppose you wanted to start off with an empty rating. Once the user selects a value, you want to pull down the newly calculated average for all ratings. The following code would allow you to achieve this:
void Page_Loaded(object sender, RoutedEventArgs e)
{
StarSelector1.DisplayValue = 0;
}
private void StarSelector1_ValueChanged(object sender, RoutedEventArgs e)
{
// Calculate Average including (StarSelector1.Value)
StarSelector1.DisplayValue = GetCalculatedAverage();
}
Half-Star Templatability

Maximum Property
The Maximum property allows you to specify the number of stars that will be displayed on the control. The default value is 5.
ReadOnly Property
Sometimes you just need to show a rating without allowing the user to interact with the control. The ReadOnly property allows for this. The default value is false.
Disabled Property
The new star selector control also has a Disabled property. You can also provide a Disabled state in the control template if you wish. The default value is false.


You can try out a live demo of the control and download the source code below:
Live Demo
Enjoy!
As you probably already know, there are quite a few ways to pass data to a Silverlight application.
- Use InitParams in the Silverlight plugin declaration
- Read data off the querystring
- Use WebClient to request a value
- Interact with the HTML DOM to pull a value from the hosting page
But what do you do if you don’t have control over the hosting page? Really, your only option is to make a call to a web server using WebClient. But even that can have cross-domain policy implications. Besides, that’s a lot of work to be doing just to simply supply a small amount of data to your application.
There is one other option however.
Application.Current.Host.Source will provide you with the URI of the XAP package that the host will render. So what this means is that when you provide the URI for your XAP package, you can append a querystring to the end, like so:
<param name="source" value="ClientBin/MyApp.xap?MyKey=Testing"/>
Now, you simply need to read (and parse) the querystring in your application. Since Silverlight does not automatically parse the querystring for us, we have to do the dirty work. Yes, there are many ways you can do achieve this. Below, you will find one technique:
private string GetXapPackageQueryStringValue(string key)
{
if (string.IsNullOrEmpty(key))
return string.Empty;
key = key.ToLower();
string xapPackage = Application.Current.Host.Source.OriginalString;
int questionMarkIndex = xapPackage.IndexOf('?');
if(questionMarkIndex == -1)
return string.Empty;
string queryString = xapPackage.Substring(questionMarkIndex, xapPackage.Length - questionMarkIndex);
queryString = queryString.Replace("?", string.Empty).ToLower();
string[] keyValuePairs = queryString.Split(new[] { '&' });
for (int i = 0; i < keyValuePairs.Length; i++)
{
string[] pair = keyValuePairs[i].Split(new[] { '=' });
if (pair[0] == key)
{
return pair[1];
}
}
return string.Empty;
}
Then, you can retrieve the querystring value like so:
string val = GetXapPackageQueryStringValue("MyKey");
// TODO: Use val in your code.
This can be useful in situations when you have the ability to specify the path to a XAP package, but don’t have control over any other facets. One example of this would be CodePlex. On CodePlex, you have the ability to embed Silverlight applications in your Wiki. You do this with the following syntax:
{silverlight:url=http://mydomain.com/MyApp.xap?MyKey=testing,height=300,width=500}
Now, you can build one application and reference it multiple times while varying the querystring for each declaration. This is really helpful when you want to write one Silverlight application that behaves differently when you change the querystring. For example, on Silverlight Contrib, we have a tutorial application that will display one control for each different parameter that is passed in.