Print Page | Close Window

Silverlight 5 Improvement to Code Sample: Simple combo box (Silverlight)

Printed From: IdeaBlade
Category: DevForce
Forum Name: DevForce 2010
Forum Discription: For .NET 4.0
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=3294
Printed Date: 16-Apr-2024 at 3:36am


Topic: Silverlight 5 Improvement to Code Sample: Simple combo box (Silverlight)
Posted By: mandpd
Subject: Silverlight 5 Improvement to Code Sample: Simple combo box (Silverlight)
Date Posted: 23-Feb-2012 at 10:03pm
Hi All,
 
I thought this might be of general interest to those, like me, who have struggled with populating look-up combo boxes when the combo box control is nested in a control which sets the datacontext away from the page viewmodel. This is such a common requirement with just about any LOB application that supports database edits.
Ward's presentation in the code sample section entitled "Simple combo box (Silverlight)" was a great help as he describes a "shim" to allow the combobox to retrieve a pointer to the viewmodel via a static resource "ViewModelLocator" which points to a class that holds a reference to the viewmodel object. This requires some code to populate the reference object in the ViewModelLocator, a resource entry, and a static resource reference in the binding. You can download the source code from the IdeaBlade site, but the main markup is on the combo box:-

<ComboBox Grid.Row="3" Grid.Column="1" x:Name="Manager"

ItemsSource="{Binding VM.CandidateManagers, Mode=TwoWay, Source={StaticResource ViewModelLocator}}"

SelectedItem="{Binding Manager, Mode=TwoWay}" HorizontalAlignment="Left" Width="176" Margin="0,4"/>.

All this is necessary because Silverlight did not support Ancestor Relative source binding (unlike WPF). Well, with Silverlight 5, this changed. You can utilise this feature to remove the need for the shim. The following markup achieves the same result.

<ComboBox Grid.Row="3" Grid.Column="1" x:Name="Manager"

ItemsSource="{Binding DataContext.CandidateManagers, Mode=TwoWay, RelativeSource={RelativeSource AncestorType=Grid, AncestorLevel=2 }}"

SelectedItem="{Binding Manager, Mode=TwoWay}" HorizontalAlignment="Left" Width="176" Margin="0,4"/>

 

 

 



Replies:
Posted By: WardBell
Date Posted: 24-Feb-2012 at 1:15pm
Yes that works for SL5
 
The downside is that you have made your template XAML (presumably this is in a template) aware of the structure of its parent. In your example, it knows the template is hosted inside a Grid that is two levels up. That awareness makes the template more brittle than we might like.
 
If you weren't using a template, you'd probably have used ElementName binding (available in SL4 ... and before?).
 
There is no perfect answer in XAML I'm afraid.
 
Thanks for these thoughts. Very helpful.



Print Page | Close Window