In my application, I want to allow the user to load several arbitrary XAML files. Internally, I use XamlReader.Load() to load the XAML.
Now, it may happen that some of the XAMLs have named controls, such as
<Button Name="button" ... />
If the user accidentally loads 2 XAMLs that define the same name, an exception occurs, saying
Could not register named object. Cannot register duplicate name "button" in this scope.
So my next step was to unregister all names before loading the XAML:
foreach (FrameworkElement child in ((Grid) Content).Children)
{
if (!string.IsNullOrEmpty(child.Name))
{
UnregisterName(child.Name);
}
}
However, that's not sufficient, I still can't load the XAML for the same reason.
How do I get rid of the name of a control?
Note: while doing research on this, I found many answers for the question "How do I remove a control by its name?". That's not what I want. I want to keep the control, but un-name it.
Note: I'm not looking for workarounds. I know that I could e.g. process the XAML as plain XML, remove the names and then load it. I'd really like to know whether and how it's possible to do that in a WPF way.
I have also tried:
- change the name with
child.Name = null; - changing the scope with
NameScope.SetNameScope(this, new NameScope()); - combinations of the above