I get the folowing error in my Silverlight application. But i cant figure out what control it is that is the problem. If i debug it don't break on anything in the code, it just fails in this framework callstack with only framework code. Is there any way to get more information on what part of a Silverlight app that is the problem in this case.
Message: Sys.InvalidOperationException: ManagedRuntimeError error #4004 in control 'Xaml1': System.InvalidOperationException: Element is already the child of another element.
at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
at MS.Internal.XcpImports.Collection_AddValue[T](PresentationFrameworkCollection`1 collection, CValue value)
at MS.Internal.XcpImports.Collection_AddDependencyObject[T](PresentationFrameworkCollection`1 collection, DependencyObject value)
at System.Windows.PresentationFrameworkCollection`1.AddDependencyObject(DependencyObject value)
at System.Windows.Controls.UIElementCollection.AddInternal(UIElement value)
at System.Windows.PresentationFrameworkCollection`1.Add(T value)
at System.Windows.Controls.AutoCompleteBox.OnApplyTemplate()
at System.Windows.FrameworkElement.OnApplyTemplate(IntPtr nativeTarget)
The XAML for the AutoCompeletBox that is in the context is:
<tk:AutoCompleteBox
x:Name="acName"
Grid.Row="0"
Grid.Column="1"
LostFocus="acName_LostFocus"
Height="20"
Width="80"
HorizontalAlignment="Left"/>
The error is a generic catch-all exception that has many many causes. I've written a debugger utility that can help to identify which part of the XAML is actually causing the error. You can download it from my blog: http://whydoidoit.com/2010/08/30/debug-xaml-element-is-already-the-child-of-another-element/
Your items may be visual elements, instead of data objects.
If you provide the XAML, I can help make sure that is the case.
Usually this error occurs when the said Element is already attached to an existing Parent and somewhere in your code you're attempting to re-parent it (ie via just straight "add" when you in turn must remove the child from the parent first, then Add it to the children etc).
Where specifically the control is failing the above isn't enough info to digest.
Simple and stupid solution:
public class AutoCompleteTextBox : AutoCompleteBox
{
public override void OnApplyTemplate()
{
try
{
base.OnApplyTemplate();
}
catch { }
}
}
Related
I'm trying to implement binding validation using Silverlight on Windows Phone, but all I get is the debugger breaking on an unhandled exception instead, and the validation not happening.
I'm following the recommendations from an MSDN article on Data Binding.
Here is what I have tried to do to set it up:
Debug -> Exceptions -> Common Language Runtime Exceptions - User-unhandled is unchecked
On the data template for the ListBoxItem, I declare two-way binding with validations:
<TextBox x:Name="LastReadingValue" Text="{Binding LastReadingValue, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" />
In the setter I raise an exception if the TextBox data is incorrect:
public string LastReadingValue
{
get
{
return _lastReadingValue;
}
set
{
try
{
double reading = System.Convert.ToDouble(value);
_lastReadingValue = String.Format("{0:0.00}", reading);
}
catch (FormatException fe)
{
throw new Exception("The meter reading must be a number like 7561.41");
}
NotifyOfPropertyChanged("LastReadingValue");
}
}
On the ListBox I declare the handler for the BindingValidationError event:
<ListBox x:Name="NewMeterReadingsListBox" ItemsSource="{Binding Meters}" ItemTemplate="{StaticResource NewMeterReadingDataTemplate}" BindingValidationError="ListBox_BindingValidationError"/>
The handler for the BindingValidationError never gets called:
private void ListBox_BindingValidationError(object sender, ValidationErrorEventArgs e)
{
Debug.WriteLine("BindingValidationError");
}
Ok - 2nd try at an answer.
A couple of interesting things happened when I tried this myself. I started from the WindowsPhoneDataboundApplication then added a TextBox and validation to the app's ListBox. I'm using the WP Mango Beta 2 tools (not the Beta 2 update from yesterday).
When debugging: if an invalid value is entered I get a debug break and prompt from VS on the throw line says that the exception is unhandled. HOWEVER: the BindingValidationError handler is called fine, the application keeps running and Application.UnhandledException isn't called.
In the _BindingValidationError function the Debug.WriteLine text is often difficult to spot with the other exception text in the output window. If you make it more obvious by forcing a new line you should spot the text:
Debug.WriteLine("\n\n*** BindingValidationError ***\n");
So basically it's working for me, but there are a couple of things to watch out for when debugging.
If you're targetting WP Mango I'd recommend you consider the Silverlight 4 way of doing data validation which doesn't involve throwing and catching exceptions - I agree with Claus insofar as using exceptions is a really ugly way of doing validation. The SL4 alternative involves implementing the IDataErrorInfo and INotifyDataErrorInfo interfaces in your bound class. I haven't tried this approach personally myself though.
Edit:
If you really want to turn off the break on exceptions you can do it from the VS2010 "Debug" menu, "Exceptions" item. Then de-select the exception type you don't want VS to do break on if it is unhandled.
If you create your own custom Exception class just for binding validation and disable the debug break only for that Exception type, then you will be able to have normal VS behaviour for your app's exceptions except when when dealing with binding failures.
I have bound a WPF ListView to a list of articles and I have that kind of binding on a certain column:
DisplayMemberBinding="{Binding Path=ArticleSupplier[0].reference, Mode=OneWay}"
The problem is that certain articles have no ArticleSupplier item, so it throws an "invisible" binding exception (in the debugger output). It doesn't affect my software itself, but it really slows down the scrolling speed of my ListView, I have about 15000 items in it. If I remove this column binding, all is smooth again.
How can I avoid these exceptions to slow down my ListView?
Try setting a fallback-value.
Bind to another Property as follows:
DisplayMemberBinding="{Binding Path=FirstArticleSupplier.reference, Mode=OneWay}"
and in the DataContext class have a property for FirstArticleSupplier as follows:
public <your ArticleSupplier class> FirstArticleSupplier
{
get { if( ArticleSupplier.Count > 0)
return ArticleSupplier[0];
return new <your ArticleSupplier class>; //this will at least not know exception and return empty object instead
}
}
Exceptions are slow in .NET. You have to avoid them in this case. Instead of trying to access a possibly empty list, you need to extract the right valu, or null, without throwing an exception:
public string FirstSupplierReference {
get {
var firstSupplier = ArticleSupplier.FirstOrDefault();
return firstSupplier != null
? firstSupplier.reference
: null;
}
}
Of course, you have to send PropertyChanged notifications everytime ArticleSupplier[0] or its reference change.
I've found that there is a significant speed difference with binding exceptions when the debugger is attached (i.e. much, much slower). Have you tried running it without the debugger attached?
Obviously better if you can avoid the exceptions entirely, but just thought I'd throw in my 2p...
I'm using PRISM in a SilverLight 4 application. I have a problem where views registered to some regions doesn't get displayed.
When loading a module at startup I register some views to regions as follows:
RegionManager.RegisterViewWithRegion("MyRegion1", typeof(IMySubView1));
RegionManager.RegisterViewWithRegion("MyRegion2", typeof(IMySubView2));
I have a view implementing an interface called IMyView, where the xaml have two contentcontrols with regions defined in a grid like this:
<ContentControl Regions:RegionManager.RegionName="MyRegion1" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" Grid.Row="0" Grid.RowSpan="1"/>
<ContentControl Regions:RegionManager.RegionName="MyRegion2" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" Grid.Row="1" Grid.RowSpan="1"/>
I have tried two different methods for adding the view to the main region. Both adds the view and basic elements such as buttons get displayed, but the regions defined in the view does not get filled with associated views.
Method 1:
object obj = _container.Resolve<IMyView>();
IRegion mainRegion = _regionManager.Regions["MainViewRegion"];
IRegionManager scoped = mainRegion.Add(obj, "test", true);
mainRegion.Activate(obj);
// Enabling the following call, it will fail saying the region MyRegion1 does not exist. Feels like it should?
// IRegion myRegion = scoped.Regions["MyRegion1"];
Method 2:
object obj = _container.Resolve<IMyView>();
_regionManager.AddToRegion("MainViewRegion", obj);
_regionManager.Regions["MainViewRegion"].Activate(obj);
It feels like the regions defined in the xaml file doesn't get registered, and because of that the registered views do not get displayed.
The MainViewRegion is defined in the shell in a TabControl as this:
<TabControl Margin="8,0,8,8" Regions:RegionManager.RegionName="MainViewRegion">
Any suggestions on solving my problem will be greatly appreciated!
I'm facing the same problem. The idea is that for whatever reason view injection {mainRegion.Add(obj, "test", true)} for already created regions doesn't show the view. A workaround that worked for me, is to create the region from code, and then inject the view. Something like this:
Microsoft.Practices.Composite.Presentation.Regions.RegionManager.SetRegionManager(headerRegionContainer, _RegionManager);
Microsoft.Practices.Composite.Presentation.Regions.RegionManager.SetRegionName(headerRegionContainer, regionName);
var view = _UnityContainer.Resolve(bag.HeaderViewType);
_RegionManager.Regions[regionName].Add(view);
_RegionManager.Regions[regionName].Activate(view);
Unfortunately for me I can't reach my goal this way, but maybe you can.
Regards,
Levente
After many hours of troubleshooting I found something.
In Composite.Presentation\Regions\RegionManager.cs there is a method called IsInDesignMode. When a region is about to be created this method is called, and if this method returns true the region is not created. See below:
private static void OnSetRegionNameCallback(DependencyObject element, DependencyPropertyChangedEventArgs args)
{
if (!IsInDesignMode(element))
{
CreateRegion(element);
}
}
private static bool IsInDesignMode(DependencyObject element)
{
// Due to a known issue in Cider, GetIsInDesignMode attached property value is not enough to know if it's in design mode.
return DesignerProperties.GetIsInDesignMode(element) || Application.Current == null
|| Application.Current.GetType() == typeof(Application);
}
When our silverlight application starts up and the regions in the shell gets created everything is fine, the Application.Current property is of type "MyName.Shell.App". But when a view gets added after startup, as a response to user input, the Application.Current type is suddenly of type "Application", and thus the IsInDesignMode method returns true and the regions are not created.
If I remove the Application.Current conditions everything works as expected. So the question is, is there something wrong in my application or is there something wrong in the prism source code?
where is your _regionManager coming from ?
Did you write a proper BootStrapper
?
You need to write a class inheriting from MefBootstrapper or UnityBootstrapper (or a custom one if you're not using neither of those IoC/Extension framework) in order to register all your needed types within the IoC container.
could you post the BootStrapper code ?
The problem is gone in Prism version 4.0, I was running Prism version 2.2 when the problem occured.
I created this class where I wanted to override this specific event for the content control.
public class MyContentControl : ContentControl
{
protected override void OnKeyUp(KeyEventArgs e)
{
//do something
//..........
e.Handled = true;
}
}
However when I am using this control in my XAML everything compiles and works fine, but I am getting a runtime exception and I am not sure exactly why? Could someone point me in the right directions....
The exception I get is
XamlParseException
UPDATED (Shows where abouts of the exceptions)
In the XAML I have:
xmlns:ctrls="clr-namespace:SilverlightProject.CustomControls"
and I use it like:
<ctrls:MyContentControl Grid.Column="0" x:Name="_contentControl" VerticalAlignment="Center" HorizontalAlignment="Center" />
Content controls require a default template to be created somewhere (e.g. in generic.xaml). They do not have a matching XAML file like user controls.
If you can provide more information, I can show you how to create an appropriate template.
There are many reasons for this.
To start with. Give the fully qualified namespace.
Instead of
xmlns:ctrls="clr-namespace:SilverlightProject.CustomControls"
Use
xmlns:ctrls="clr-namespace:SilverlightProject.CustomControls;assembly=YourAssebmlyName"
If that, doesn't help.
You directly attach your control with the application. Then, enable Debug -> Exceptions. Check Thrown option for the CLR execetion checkbox. You have fair amount of possibility to get to know the cause.
I'm trying to create a UserControl that inherits from a generic class. It does not directly inherit from a generic class, but through an intermediate class that does not use generics. This compiles and works at runtime, but I get an error at design time.
Here's my generic parent class:
Public Class GenericParent(Of T)
Inherits UserControl
End Class
Here's my non-generic parent class:
Public Class NonGenericParent
Inherits GenericParent(Of String)
End Class
Here's my XAML:
<local:NonGenericParent x:Class="SilverlightApplication5.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SilverlightApplication5"
Width="400" Height="300">
<StackPanel>
<Button Content="Hello"/>
</StackPanel>
</local:NonGenericParent>
The IntelliSense parser gives the following errors:
The property 'Width' was not found in type 'NonGenericParent'.
The property 'Height' was not found in type 'NonGenericParent'.
The type 'NonGenericParent' does not support direct content.
It is as though IntelliSense can't see up the inheritance tree past the GenericParent class. I've tried specifying the ContentPropertyAttribute directly on the SilverlightApplication5.Page class, the NonGenericParent class, and it does not work.
I've read that the TypeArguments attribute is not supported in Silverlight 2.0. That is why I've created the intermediate NonGenericParent class.
If anybody has any ideas how to silence these errors I'd be eager to hear them.
Update: We've opened a support ticket with MSFT, I'll update this with whatever their solution is.
We've received word from Microsoft that this is not likely to be fixed in future versions. After they bounced the problem around trying to find the responsible group, it appears that this problem belongs to their WPF developer group, which is where the 'not going to fix it' answer came from.
In the meantime, we've updated our code to yank out the generics from the parent classes until I guess XAML 2009.
Not sure about silverlight, but this compiles and runs as expected in c#:
class GenericObject[T] : UserControl
{
}
class StaticObject : GenericObject[Int32]
{
public Int32 wide { get { return this.Width; } }
}
private void Form1_Load(object sender, EventArgs e)
{
StaticObject so = new StaticObject();
this.Text = so.wide.ToString();
}
So if it compiles against the clr, it should work just fine.
Could be just an intellisense bug as you're suggesting. Normally I'd advise against ignoring comiler warnings, but in this case it seems that the warning is not valid.
edit: substituted angle brackets with square brackets cause SO stripped them.
Despite being at 2.0 silverlight (and especially the VS2008 tweaks for silverlight) are still very young. There are still quirks in the IDE stuff.
Do you still have the problem even after a sucessful build?
This blog post seems to be related to your issue:
http://blogs.msdn.com/b/wpfsldesigner/archive/2010/01/22/known-issue-controls-deriving-from-a-generic-base-class-must-be-in-separate-assembly.aspx
For Silverlight it seems that you must have 3 classes for this to work.