tags:

views:

100

answers:

1

In my Silverlight app I have an event handler that dynamically creates a new instance of a user control and adds it to the Content property of another control. This works just fine without error UNTIL I assign a name (x:Name="") to the user control (not in the event, but within the XAML of the user control. Then, when I set the template to the .Content property of the control I get a "System.ArgumentException was unhandled by user code / Value does not fall within the expected range." exception. I have no clue where the error is or where to look... it's pretty much embedded within SL. Can't figure out what other property I need to set.

Here's the code that adds the user control:

TilePane p = e.Element as TilePane; // this is the target
AppTileNormalViewControl template = new AppTileNormalViewControl(); // this is the user control
p.Content = template; // error happens here

The problem here is that the user control has a few public properties that I was going to use for databinding to some of the controls in the user control. I need a name to do the syntax:

Text="{Binding ElementName=UserControlName, Path=PublicProperty}"

Without the ElementName, the binding isn't working. So, if I specify the name binding will work, but I can't get the control added. Ideas?

+1  A: 

The problem is that the Name property of the UserControl will become part of the set of available element names in scope to which your content control belongs to. As soon as you attempt to add two of these elements in this way you end up trying to add the same name which results in the error you are seeing.

The name of the UserControl is really the business of the consumer of the usercontrol not the user control itself so you should remove this x:Name. An alternative that does work is like this:-

Text="{Binding Parent.PublicProperty, ElementName=LayoutRoot}"

A Usercontrol contains a single root element into which you place all of its UI and this element (which is usually a Grid but can actually be any FrameworkElement) is normally names LayoutRoot. A FrameworkElement has a Parent property which in the case of the layout root of a UserControl will the the UserControl itself.

AnthonyWJones
Thanks... that did the trick. Your snippet is missing the Path property. This is what did it for me (my public property is named PaneTitle:Text="{Binding ElementName=LayoutRoot, Path=Parent.PaneTitle}"
AC
@AC: I tested with the `Path=` missing and it works fine, but it is just a bit of syntatic sugar and it is probably better to be explicit.
AnthonyWJones