Dynamically adding user controls in with names throws "invalid range exception" Silverlight
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 templ开发者_如何学Pythonate 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?
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.
精彩评论