“Value does not fall within the expected range.” when adding a UserControl to a Panel

This just took me a while to puzzle out. I’d built a custom UserControl which worked perfectly while I was initially testing it, but when I modified the application so that I was using several of them, all of a sudden any attempt to add the control to the panel was giving the error “Value does not fall within the expected range.” But it wasn’t giving any clue as to which value was the problem.

One reason it took me a little longer to find the solution is that as well as this custom control (which has a bunch of visual states) I was inserting it into a custom panel, so I wasn’t sure if my code in the panel was causing the problem. But in the end it was something fairly obscure.

My control had an x:Name attribute set on its UserControl root element, added by Blend as part of the visual transitions, and trying to add two copies of the control to the panel meant adding two things with the same name attribute, which is forbidden, and it’s this which was causing the error. If I removed the name attribute, all worked normally.

This does raise an issue, though. If you can’t set a name attribute, how do you declaratively define storyboards which affect properties on the root usercontrol itself? I still don’t know the answer to this. Luckily, I’d already refactored my control such that the transitions could be applied to the LayoutRoot container instead, but that might not be a solution for all scenarios.

Advertisements

2 comments

  1. I worked around it by moving the animations to the child container (the LayoutRoot). You just have to avoid doing anything that requires animating properties on the UserControl. Most things that I can think of can be moved down to the child container, which works fine.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s