While working on Bumble Beegger we came across a daunting problem that only seemed to happen under certain conditions.
Silverlight error message
ErrorCode: 4002
ErrorType: ManagedRuntimeError
Message: System.Exception: Error HRESULT E_FAIL has been returned from a call to a COM component.
at MS.Internal.XcpImports.MethodEx(IntPtr ptr, String name, CValue[] cvData)
at System.Windows.DependencyObject.MethodEx(String methodName, CValue[] cvData)
at System.Windows.UIElement.ReleaseMouseCapture()
at System.Windows.Controls.Primitives.ButtonBase.ReleaseMouseCaptureInternal()
at System.Windows.Controls.Primitives.ButtonBase.OnLostFocus(RoutedEventArgs e)
at System.Windows.Controls.Primitives.ButtonBase.OnLostFocus(Object sender, RoutedEventArgs e)
at System.Windows.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)
After a few hours of debugging, experimenting and googling I came across a discussion on Silverlight.net that shed some light on the problem.
As it turns out there is bug in Silverlight 2 beta 1 that can cause a crash when changing the visibility of a button control inside a mouse event handler.
The recommended workarounds around this problem were to change the size to 0,0 or change the opacity to 1.
Another option is to use the Canvas.ZIndexProperty and set it to a number that is smaller then your foreground elements.
The problem is that those does not always produce a similar enough effect in other elements.
If you still want to use visibility where possible, you can check the type of control and choose to modify visibility, size, opacity or Z Index according to the type.
Granted this is a horrible hack but it gets the job done until we can get our hands on beta 2...
Example:
// assume uiElement points to some valid UIElement
UIElement uiElement;
// check element type, if its not a button set visibility to collapsed else use ZIndex for a similar effect
if (uiElement.GetType() != typeof(Button))
uiElement.Visibility = Visibility.Collapsed;
else
((Button)uiElement).SetValue(Canvas.ZIndexProperty, -1);