2011-03-29 9 views
5

Mi aplicación es multi-ventana. Si se produce una XamlParseException, toda la aplicación se cierra.¿Cómo puedo evitar el apagado de toda la aplicación en XamlParseException

Lo que me gustaría hacer, como máximo, es cerrar la ventana 'responsable' de este error.

¿Conoces alguna forma de lograrlo?

Un ejemplo Excepción:

System.Windows.Markup.XamlParseException: Provide value on 'System.Windows.Markup.StaticResourceHolder' threw an exception. ---> System.Exception: Cannot find resource named 'PasteCommandRef'. Resource names are case sensitive. 
    at System.Windows.StaticResourceExtension.ProvideValueInternal(IServiceProvider serviceProvider, Boolean allowDeferredReference) 
    at System.Windows.StaticResourceExtension.ProvideValue(IServiceProvider serviceProvider) 
    at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CallProvideValue(MarkupExtension me, IServiceProvider serviceProvider) 
    --- End of inner exception stack trace --- 
    at System.Windows.Markup.XamlReader.RewrapException(Exception e, Uri baseUri) 
    at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlReader templateReader, XamlObjectWriter currentWriter) 
    at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlObjectWriter objectWriter) 
    at System.Windows.FrameworkTemplate.LoadOptimizedTemplateContent(DependencyObject container, IComponentConnector componentConnector, IStyleConnector styleConnector, List`1 affectedChildren, UncommonField`1 templatedNonFeChildrenField) 
    at System.Windows.FrameworkTemplate.LoadContent(DependencyObject container, List`1 affectedChildren) 
    at System.Windows.StyleHelper.ApplyTemplateContent(UncommonField`1 dataField, DependencyObject container, FrameworkElementFactory templateRoot, Int32 lastChildIndex, HybridDictionary childIndexFromChildID, FrameworkTemplate frameworkTemplate) 
    at System.Windows.FrameworkTemplate.ApplyTemplateContent(UncommonField`1 templateDataField, FrameworkElement container) 
    at System.Windows.FrameworkElement.ApplyTemplate() 
    at System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
    at System.Windows.UIElement.Measure(Size availableSize) 
    at System.Windows.Controls.Primitives.UniformGrid.MeasureOverride(Size constraint) 
    at System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
    at System.Windows.UIElement.Measure(Size availableSize) 
    at MS.Internal.Helper.MeasureElementWithSingleChild(UIElement element, Size constraint) 
    at System.Windows.Controls.ItemsPresenter.MeasureOverride(Size constraint) 
    at System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
    at System.Windows.UIElement.Measure(Size availableSize) 
    at System.Windows.Controls.Border.MeasureOverride(Size constraint) 
    at System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
    at System.Windows.UIElement.Measure(Size availableSize) 
    at System.Windows.Controls.Control.MeasureOverride(Size constraint) 
    at System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
    at System.Windows.UIElement.Measure(Size availableSize) 
    at System.Windows.Controls.Grid.MeasureCell(Int32 cell, Boolean forceInfinityV) 
    at System.Windows.Controls.Grid.MeasureCellsGroup(Int32 cellsHead, Size referenceSize, Boolean ignoreDesiredSizeU, Boolean forceInfinityV) 
    at System.Windows.Controls.Grid.MeasureOverride(Size constraint) 
    at System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
    at System.Windows.UIElement.Measure(Size availableSize) 
    at System.Windows.Controls.Grid.MeasureCell(Int32 cell, Boolean forceInfinityV) 
    at System.Windows.Controls.Grid.MeasureCellsGroup(Int32 cellsHead, Size referenceSize, Boolean ignoreDesiredSizeU, Boolean forceInfinityV) 
    at System.Windows.Controls.Grid.MeasureOverride(Size constraint) 
    at System.Windows.FrameworkElement.MeasureCore(Size availableSize) 
    at System.Windows.UIElement.Measure(Size availableSize) 
    at System.Windows.ContextLayoutManager.UpdateLayout() 
    at System.Windows.ContextLayoutManager.UpdateLayoutCallback(Object arg) 
    at System.Windows.Media.MediaContext.InvokeOnRenderCallback.DoWork() 
    at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks() 
    at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget) 
    at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget) 
    at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) 
    at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
+6

Respuesta estúpida, pero evitar XamlParseException sería la mejor manera de manejarlo. Es una excepción muy crítica (lo que probablemente significa que sucedió algo al inicializar los controles), ignorarlo simplemente matará su look'n'feel de la interfaz de usuario:/ – Damascus

Respuesta

2

En su ejemplo, la aplicación se cuelga porque no puede encontrar un recurso que estáticamente al que se hace referencia a través de la extensión de marcado StaticResource. Le está diciendo a WPF que este recurso existe mejor cuando vaya a buscarlo. Entonces, por supuesto, tendrá un problema con eso.

Para arreglar su ejemplo específico (evitando la excepción cuando no se encuentra el recurso) puede cambiar usando la extensión de marcado DynamicResource. Esto le indicará a WPF que el recurso podría existir cuando vaya a buscarlo y WPF estará más relajado al lanzar excepciones para este ejemplo.

En general, siempre debe proporcionar un controlador de excepciones de nivel raíz para su aplicación WPF, como señaló Wesley con el método App_HandledExcpetion.

Pero simplemente tragar ciegamente XAMLParseException va a provocar MUCHO más problemas en su aplicación que serán difíciles de depurar con las excepciones que se tragan.

1

Puesto que no se puede envolver en XAML Try..Catch blocks, tendrá que cargar la fuente de datos a través de código, que envuelva en el manejo de excepciones, y validar la fuente de datos es XML válido antes de atarlo.

También puede ver excepciones no controladas, en App.Application_UnhandledException y no es tan elegante.

+0

En el ejemplo de la aplicación, no sé dónde tengo que poner el Prueba ... bloque de captura. Tienes una idea ? – manuc66

+0

Hay muchos ejemplos en línea si busca 'XAML Try Catch', como http://www.eggheadcafe.com/tutorials/aspnet/5d2dda03-0791-4eca-8a2c-a4d2a2d0244b/exception-handling-made-easy-in -xaml-applications.aspx, y para las excepciones no controladas no especifica try..catch, solo maneja el evento en la clase de la aplicación. – invert

Cuestiones relacionadas