XamlParseException: '' is not a valid value for property 'RuntimeVisibility'? - wpf

While editing a WPF custom control the design view in Visual Studio 2019 ran into this error:
(entire exception details down below).
Web searches have turned up nothing useful for RuntimeVisibility, although there are other similarly worded "is not a valid value" messages they seem quite varied. I can't even find the term "RuntimeVisibility" almost at all related to WPF.
So I tried to debug the VS2019 designer process by attaching to XDesProc in a separate VS2019 instance. By enabling trapping of all exceptions it would indeed break when the control in question was loaded into the designer. But it isn't failing in any user-level code; the problem emerges from somewhere deep inside the framework and the debugging information at that stack frame is meaningless to me.
I'm looking for a methodology or advice to track down the root cause of this problem. While it's annoying in the designer I'm more concerned if this could lead to an error at runtime. As noted, the mysterious RuntimeVisibility property doesn't seem like a designer-specific issue.
Full exception info:
XamlParseException: '' is not a valid value for property 'RuntimeVisibility'.
StackTrace
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()
InnerException: '' is not a valid value for property 'RuntimeVisibility'.
ArgumentException: '' is not a valid value for property 'RuntimeVisibility'.
StackTrace
at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
InnerException: None

After I gave up on debugging XDesProc I resorted to commenting things in/out in the XAML just on a hunch to see if I could locate the problem. I didn't specifically know that it originated in the XAML but that turned out to be the case.
By working "outside-in" (meaning, comment out almost the entire body of the XAML, and then gradually add things back in) I was able to narrow it down to one line that, when removed, also eliminates the error:
<Canvas
ToolTipService.IsEnabled="{c:Binding ShowToolTip}"
Visibility="{c:Binding IsVisible}"
>
where c:Binding refers to:
xmlns:c="clr-namespace:CalcBinding;assembly=CalcBinding"
(https://github.com/Alex141/CalcBinding)
When the Visibility attribute is removed, the error goes away.
What c:Binding is doing here is automatically converting between a bool property in the viewmodel and a proper Visibility value. This normally works fine, but I can just replace it with with a normal binding and a converter to work around the problem.

Related

WPF XAML Designer Crashes

I have a Window, the only thing it has in it is a TextBlock. I'm getting ridiculous designer exceptions that is crashing the designer every time I change anything. I started removing everything trying to find the culprit of this error. And now I have nothing left, but the designer keeps throwing exceptions.
<Window x:Class="Company.Product.Views.About"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="397"
Width="658">
<TextBlock>Test</TextBlock>
</Window>
code behind:
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class About : Window
{
public About()
{
InitializeComponent();
}
}
If I "Click here to reload the designer" the window shows up, but then if I modify the text of TextBlock, I get an exception
Exception
System.ArgumentNullException
Value cannot be null.
at System.RuntimeType.MakeGenericType(Type[] instantiation)
at Microsoft.VisualStudio.Shell.Design.VsTargetFrameworkUtil.GetRuntimeType(Type type)
at Microsoft.VisualStudio.Shell.Design.VsTargetFrameworkType.TryGetRuntimeType()
at Microsoft.VisualStudio.Shell.Design.VsTargetFrameworkUtil.EnsureRuntimeType(Type type)
at Microsoft.VisualStudio.Shell.Design.VsTargetFrameworkProvider.GetRuntimeType(Type reflectionType)
at MS.Internal.Package.VSIsolationProviderService.RemoteReferenceProxy.VsReflectionResolver.GetRuntimeType(Type reflectionType)
at Microsoft.Windows.Design.Metadata.ReflectionMetadataContext.CachingReflectionResolver.GetRuntimeType(Type reflectionType)
at Microsoft.Windows.Design.Metadata.ReflectionMetadataContext.Microsoft.Windows.Design.Metadata.IReflectionResolver.GetRuntimeType(Type reflectionType)
at MS.Internal.Metadata.ClrType.get_RuntimeMember()
at MS.Internal.Metadata.ClrMember`1.Microsoft.Windows.Design.Metadata.Reflection.IReflectionMember.get_MemberInfo()
at MS.Internal.Metadata.ClrType.Equals(Object obj)
at System.Collections.Generic.ObjectEqualityComparer`1.Equals(T x, T y)
at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
at Microsoft.Windows.Design.Metadata.Xaml.XamlExtensionImplementations.<>c__DisplayClass5.<FindAttachableProperties>b__4(ITypeMetadata walkType)
at MS.Internal.Design.Metadata.Xaml.XamlType.<GetAllAttachableProperties>d__7.MoveNext()
at MS.Internal.Design.Metadata.Xaml.XamlType.<FindAttachableProperties>d__0.MoveNext()
at Microsoft.Windows.Design.Metadata.Xaml.XamlExtensionImplementations.<FindAttachableProperties>d__7.MoveNext()
at MS.Internal.VirtualModel.VirtualModelPropertyCollection.<GetUncachedProperties>d__0.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at MS.Internal.VirtualModel.VirtualModelPropertyCollection.GetEnumerator()
at MS.Internal.Designer.PropertyEditing.Model.Properties.ModelPropertyMerger.<GetFirstProperties>d__0.MoveNext()
at MS.Internal.Designer.PropertyEditing.Views.PropertyEntryReader.RedraftEntries(IPropertyViewManager viewManager, Selection selection, Boolean attachedOnly, IEventCodeBehindProxy eventCodeBehindProxy, CategoryList categoryList)
at MS.Internal.Designer.PropertyEditing.PropertyInspector.UpdateCategories(Selection selection, Boolean attachedOnly, IEntryReader entryReader)
at MS.Internal.Designer.PropertyEditing.PropertyInspector.RefreshPropertyList(Boolean attachedOnly)
at MS.Internal.Designer.PropertyEditing.PropertyInspector.OnSelectionChangedIdle()
at MS.Internal.Designer.PropertyEditing.PropertyInspector.OnSelectionChangedIdleForced(Object sender, EventArgs e)
at System.Windows.Threading.DispatcherTimer.FireTick(Object unused)
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)
I'm left with no way to debug what the problem is, and frankly I getting frustrated considering there should be nothing on this simple example that should be crashing the designer. Any ideas?
Update
After re-installing and updating and reloading, problem went away temporarily. Now the problem is back again.
Actually, I'm not sure if the problem ever went away. I've also tried VS safe mode, /resetsettings, and deleting my several cache folders in the VS folder.
Update2
Here's a screencast which shows the problem Excuse my resolution, I'm in portrait.
Alright, I believe I fixed the problem. I created a new executable project, copied everything from the old one to the new one and tried deleting or adding items one by one to figure out what was special about that project.
It turns out that I'm referencing several 3rd party libraries by Actipro. Earlier, I had upgraded the libraries and copied them to a /lib folder and referenced them from there. One of the references was forgotten though, and I believe it was targetting an older version in the GAC instead of the /lib folder. I think I basically had two different versions of Actipro's shared library referenced.
After removing the erroneous reference to the old build for the 3rd party library, and updating it to the proper version as the others, the problem has gone away
The strange thing, is that the Window in question used no component or anything from that library. It may be that it was trying to resolve the Attached Properties inside the library (from the stack trace).
Try to set the TextBlock's content in the TextBlock.Text property:
<Window x:Class="Company.Product.Views.About"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="397"
Width="658">
<TextBlock Text="Test"/>
</Window>
Maybe that is the issues.

Causes of intermitant Arg_ArgumentException on in Production deployment?

We have just recently deployed a Trusted, In-Browser, Silverlight 5 application to our Production webserver. We are getting fairly frequent ArgumentExceptions captured by the App.xaml.cs UnhandledException handler. So far we have been unable to determine the source of the exception.
We are not seeing the exception when running under the debugger (I have that explicitly enabled the exception for capture under Debug->Exceptions....). Some users see this error very frequently, while others never see the error. It doesn't seem to be a fatal error as the users can just click the OK button from the ErrorWindow that we display and everything functions normally.
To stop annoying the users, I have added a handler for ArgumentException types and just mark it as handled and continue on. However, I am still logging the errors and would really like to determine the actual source so that I can fix the problem. Just ignoring the exception doesn't seem like a long term solution.
The Stack trace is below and is the same for all ArgumentExceptions.
Any ideas on how I can troubleshoot better and determine the cause of this exception?
Thanks,
Tim
Unhandled Exception: [Arg_ArgumentException]
Arguments:
Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version=5.0.10411.00&File=mscorlib.dll&Key=Arg_ArgumentException :
at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
at MS.Internal.XcpImports.SetValue(IManagedPeerBase obj, DependencyProperty property, Double d)
at MS.Internal.XcpImports.SetValue(IManagedPeerBase doh, DependencyProperty property, Object obj)
at System.Windows.DependencyObject.SetObjectValueToCore(DependencyProperty dp, Object value)
at System.Windows.DependencyObject.SetEffectiveValue(DependencyProperty property, EffectiveValueEntry& newEntry, Object newValue)
at System.Windows.DependencyObject.UpdateEffectiveValue(DependencyProperty property, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, ValueOperation operation)
at System.Windows.DependencyObject.RefreshExpression(DependencyProperty dp)
at System.Windows.Data.BindingExpression.SendDataToTarget()
at System.Windows.Data.BindingExpression.SourceAcquired()
at System.Windows.Data.BindingExpression.PerformTargetLoaded()
at System.Windows.Data.BindingExpression.TargetLoaded(Object o, RoutedEventArgs e)
at MS.Internal.CoreInvokeHandler.InvokeEventHandler(UInt32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex

WPF DataGrid ItemsSource Binding Issue

I have a DataGrid in a WPF application that binds itself to an ObservableCollection of objects, and everything works fine.
Now if I modify a cell in the datagrid during runtime, and delete the content, leave the cell empty. The observableCollection's corresponding value will not be modified, it will be the old value. But when I exit the window containing the datagrid and restart the window, it throws a XamlParseException, says:"Set Property 'System.Windows.Controls.ItemsControl.ItemsSource' threw an exception"
StackTrace:
at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at VO3.Start.InitializeComponent() in c:\VO\Trunk\VO3\Start.xaml:line 1
at VO3.Start..ctor() in C:\VO\Trunk\VO3\Start.xaml.cs:line 103
InnerException: System.InvalidOperationException
Message='DeferRefresh' is not allowed during an AddNew or EditItem transaction.
Source=PresentationFramework
StackTrace:
at System.Windows.Data.CollectionView.DeferRefresh()
at System.Windows.Controls.ItemCollection.SetCollectionView(CollectionView view)
at System.Windows.Controls.ItemCollection.SetItemsSource(IEnumerable value)
at System.Windows.Controls.ItemsControl.OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
at System.Windows.Baml2006.WpfKnownMemberInvoker.SetValue(Object instance, Object value)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(XamlMember member, Object obj, Object value)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(Object inst, XamlMember property, Object value)
InnerException:
It won't throw the exception as long as when I closed the window, no cell in the datagrid is empty. I also checked the Collection before the Window does InitializeComponent Line and it looks perfectly fine, all the objects have the correct value, no empty or nulls. I cannot figure out why it's throwing this exception. any ideas?
Thanks in advance.
XAML:
<DataGrid HeadersVisibility="All" RowHeight="19" AutoGenerateColumns="False" Grid.Row="1" CanUserResizeColumns="False"
CanUserAddRows="False" CanUserDeleteRows="False" Block.TextAlignment="Right" Grid.RowSpan="2" CanUserReorderColumns="False"
ItemsSource="{Binding Collection}" Width="132" HorizontalAlignment="Right" Margin="10,0,10,0" CanUserSortColumns="False"
IsEnabled="{Binding ElementName=CheckBox, Path=SelectedIndex, Converter={StaticResource startEnabledConverter}}">
There appear to have been quite a few issues with the DataGrid & DeferRefresh. Here are two relevant posts:
The generic recommendation seems to be to examine the DataGrid's associated view as an IEditableCollectionView (which yours would be by default as ObservableCollection gets a ListCollectionView during binding when last I looked) and check IsAddingNew & IsEditingItem to see if it's safe to modify the view. Such modifications would include DeferRefresh, which is essentially a Disposable used to batch up modifications to the view.
As far as I can see, the problem you have is that the DataGrid is midway through a transaction, or the view is set to believe it is, whilst you are changing ItemsSource (which would change or entirely replace the associated bound view). That you are clearing out a cell but it is not yet modifying the underlying data implies it's begun an edit (BeginEdit), but not yet committed (CommitEdit), which occurs when you change cell by default.
That it is happening when you are closing & reopening the window implies that some preserved state is kept around that still thinks a transaction is in progress. Perhaps it is still using the same ListCollectionView as before, and that still has IsEditingItem set to true?
The fix is most likely to ensure that any and all edits are committed before you close the window.
if the field that you are blanking out is not of type string, then it may not be updating correctly.
for example, if it is an "int" and you blank out the cell the "int" property of your viewmodel will not get set.
The way i have fixed this problem is with a converter that converts blank values for ints into zero.
hope this helps

Exceptions are swallowed in my WPF application. How to force application to crash?

I am new to WPF, I am using VS2010 beta2, .NET 4.0.
Throw new Exception("test") in my code simply swallows exception and application does not crash.
This is not what I expect, I want the application to crash if unhandled exception occurs.
Is there a simple way to achieve this?
Also, neither Application.DispatcherUnhandledException nor AppDomain.UnhandledException is executed. It is probably because all code is executed as part of the data binding (I am using MVVM pattern and exception is thrown in ViewModel constructor).
While debugging I can look into Output window and find out what is wrong. But it seems to me odd, that application simply ignores error, leaves UI in incorrect state and does not crash.
Edit:
It seems that maybe only non-critical binding exceptions should occur while databinding. Maybe extracting functionality which is not directly related to binding (for example connecting to database) out of the binding execution can be the solution. However I am not sure how to achieve it in MVVM.
Simplified example:
XAML:
<DataTemplate DataType="{x:Type vm:ItemViewModel}">
<vw:ItemControl />
</DataTemplate>
<ContentControl
Content="{Binding Path=MyItem}"
/>
where MyItem creates and returns instance of ItemViewModel. Problem is that constructor of ItemViewModel is executed as part of the data binding and I am not sure if this is good practice (this constructor contains code which can fail - for example if database is not accessible).
You can catch the exceptions raised during binding and rethrow them - see the answer to this question.
The why's are answered here and here. They also explain ways to debug the exceptions better. No answers on how to turn them into unhandled exceptions though.
edit: You can instruct bindings to signal an error when a binding gets source updated. See here. Then you can use the ErrorTemplate (or use the default) to show the error in your UI.
{Binding Age, ValidatesOnDataErrors=true}
I will answer my question myself:
I achieved proper behavior by moving code which can fail (e.g. database access call) from (data bound) property getter to the constructor of View-Model. Additionaly I have used BackgroundWorker for this call, so code is executed asynchronously. I rethrow possible exception in RunWorkerCompleted - BackgroundWorker guarantees that it will be done on UI thread.
public TestViewModel()
{
BackgroundWorker bckgWorker = new BackgroundWorker();
bckgWorker.DoWork += ((s, e) => this.TestExecuteCode());
bckgWorker.RunWorkerCompleted += ((s, e) =>
{
if (e.Error != null)
throw e.Error;
});
bckgWorker.RunWorkerAsync();
}
private void TestExecuteCode()
{
this.DataBoundProperty = LoadDataFromDb();
}
I strongly prefer this approach of getting data asynchronously rather than IsAsync=true setting on Binding in XAML. This approach never swallows Exceptions compared to IsAsync approach when exceptions are thrown on render thread and are swallowed by default.
Warning: When running this code as part of unit tests, RunWorkerCompleted event handler will not be marshaled back to caller's thread by default. SynchronizationContext used by BackgroundWorker must be set manually in order to handle exceptions in unit tests correctly.
.Net 4.0\WPF introduces a way of doing this see answer here
I'm pretty sure a poorly designed application using .NET 4 could abuse AppDomain.FirstChanceException for this purpose.
The build log gives you everything you need to know for finding problems in your WPF application. Here's what was logged when I threw a NotImplementedException in some code I knew the UI was bound to:
System.Windows.Data Error: 17 : Cannot get 'ExitCommand' value (type 'RelayCommand') from '' (type 'ControlCenter'). BindingExpression:Path=ExitCommand; DataItem='ControlCenter' (Name='controlCenterWindow'); target element is 'MenuItem' (Name=''); target property is 'Command' (type 'ICommand') TargetInvocationException:'System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NotImplementedException: The method or operation is not implemented.
at Tvl.Client.ControlCenter.get_ExitCommand() in C:\dev\Tvl\Client\ControlCenter.xaml.cs:line 25
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
at MS.Internal.Data.PropertyPathWorker.GetValue(Object item, Int32 level)
at MS.Internal.Data.PropertyPathWorker.RawValue(Int32 k)'

Silverlight ChildWindow: HRESULT E_FAIL on ChildWindow.Show()

I have some problems with ChildWindow control, I have created an error window control that is shown after unhandled exception is caught in app.xaml.cs. The problem is when I try to show the error window, sometimes it works fine, but sometimes I get this nasty exception:
Message:
Error HRESULT E_FAIL has been returned from a call to a COM component.
Stack Trace:
at MS.Internal.XcpImports.CheckHResult(UInt32 hr) at MS.Internal.XcpImports.SetValue(INativeCoreTypeWrapper obj, DependencyProperty property, Boolean b) at System.Windows.DependencyObject.SetValue(DependencyProperty property, Boolean b) at System.Windows.Controls.Primitives.Popup.set_IsOpen(Boolean value) at System.Windows.Controls.ChildWindow.Show() at FrontEnd.SL.Util.GuiLogger.ShowErrorWindow(ErrorDetails details, ErrorSeverity severity)
the trace you see is inside the Show() method of the ChildWindow.
In another words, my code is:
ErrorWindow errorWin= new ErrorWindow();
errorWin.Show();
where ErrorWindow:ChildWindow
any help is greatly appreciated..
It seems to me that the use of a ChildWindow control is going to be prone to some problems. What happens if the incumbent VisualTree is in an inconsistent/broken state as result of the exception?
The best chance you have to "handling" an unhandled exception within the bounds of the application would be to completely replace the existing object held by the VisualRoot.
This can also happen if there is a problem loading the content of the childwindow. In my case I had specified different namespaces in a usercontrol's code-behind and its xaml, which caused this cryptic error.

Resources