wpf move project sub folder to different location - wpf

With MVVM the Images folder should be under Project folder or under View as a sub folder?
I originally have Images folder under Project folder with:
ImageBrush ImageSource="/DataTransfer;component/Images/image1.png"
and everything works fine.
Then I move the Images folder go under View folder and I specify:
ImageBrush ImageSource="/DataTransfer/View/Images/image1.png"
It throws:
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)
......
What do I need to do to fix it?

Solved.
ImageBrush ImageSource="/DataTransfer;component/View/Images/image2.jpg"
But this question is not answered yet.
With MVVM the Images folder should be under Project folder or under View as a subfolder?

Related

Create a reference to Windows system color (a value type) with a converter in XAML

I want to set up a theming system, and one of the theme should follow the Window's system colors. However because we have many more elements than there are for Windows system color, we have a need to adjust the shading of some system colors. Because colors are value types, it is difficult to substitute them with something that would allow us to use a converter in the place.
For example, we have this in one of our theme XAML:
<Color x:Key="ButtonFaceColor">#FFD3D3D3</Color>
This is then referenced via the resource key in various parts of XAML, mostly with brushes but also with few other elements that accepts a color. For example, we might have a brush:
<SolidColorBrush x:Key="ButtonFaceBrush" Color="{StaticResource ButtonFaceColor}"/>
However, not only brushes use colors; we have other elements that might take the colors directly. For that reason, we want to customize using colors, rather than brushes.
Now, we want to have a theme that follows the Windows' theme. If we just want to use system color as-is, we can change this into:
<StaticResource x:Key="ButtonFaceColor" ResourceKey="{x:Static SystemColors.ControlColor}"/>
However, we actually want to use a converter so that we can adjust the shading. So we actually want something more akin to this:
<Binding x:Key="ButtonFaceColor" Source="{x:Static SystemColors.ControlColor}" Converter="{StaticResource RgbShadeConverter}" ConverterParameter="1"/>
However, testing with even only the color reference as shown:
<Binding x:Key="ButtonFaceColor" Source="{x:Static SystemColors.ControlColor}"/>
We get an error which is pretty inscrutable. Judging from the errors, it's within the XAML trying to resolve the binding and possibly might not be liking that we are basically substituting a Color struct with a Binding object that should return a Color struct.
System.Windows.Markup.XamlParseException: 'Set property 'System.Windows.ResourceDictionary.DeferrableContent' threw an exception.' Line number '3' and line position '21'. ---> System.Xaml.XamlObjectWriterException: 'Provide value on 'MS.Internal.Markup.StaticExtension' threw an exception.' Line number '105' and line position '22'. ---> System.IO.FileNotFoundException: Could not load file or assembly 'Infralution.Localization.Wpf, PublicKeyToken=547ccae517a004b5' or one of its dependencies. The system cannot find the file specified.
at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
at System.Reflection.Assembly.Load(AssemblyName assemblyRef)
at System.Windows.Baml2006.Baml2006SchemaContext.ResolveAssembly(BamlAssembly bamlAssembly)
at System.Windows.Baml2006.Baml2006SchemaContext.GetAssembly(Int16 assemblyId)
at System.Windows.Baml2006.Baml2006SchemaContext.EnsureXmlnsAssembliesLoaded(String xamlNamespace)
at System.Windows.Baml2006.Baml2006SchemaContext.GetXamlType(String xamlNamespace, String name, XamlType[] typeArguments)
at MS.Internal.Xaml.XamlContext.GetXamlType(XamlTypeName typeName, Boolean returnUnknownTypesOnFailure, Boolean skipVisibilityCheck)
at MS.Internal.Xaml.XamlContext.ResolveXamlType(String qName, Boolean skipVisibilityCheck)
at MS.Internal.Xaml.Context.ObjectWriterContext.ServiceProvider_Resolve(String qName)
at MS.Internal.Markup.StaticExtension.ProvideValue(IServiceProvider serviceProvider)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CallProvideValue(MarkupExtension me, IServiceProvider serviceProvider)
--- End of inner exception stack trace ---
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CallProvideValue(MarkupExtension me, IServiceProvider serviceProvider)
at System.Xaml.XamlObjectWriter.Logic_ProvideValue(ObjectWriterContext ctx)
at System.Xaml.XamlObjectWriter.Logic_AssignProvidedValue(ObjectWriterContext ctx)
at System.Xaml.XamlObjectWriter.WriteEndObject()
at System.Xaml.XamlServices.Transform(XamlReader xamlReader, XamlWriter xamlWriter, Boolean closeWriter)
at System.Windows.ResourceDictionary.EvaluateMarkupExtensionNodeList(XamlReader reader, IServiceProvider serviceProvider)
at System.Windows.ResourceDictionary.GetKeyValue(KeyRecord key, IServiceProvider serviceProvider)
at System.Windows.ResourceDictionary.SetKeys(IList`1 keyCollection, IServiceProvider serviceProvider)
at System.Windows.Baml2006.WpfSharedBamlSchemaContext.<>c.<Create_BamlProperty_ResourceDictionary_DeferrableContent>b__297_0(Object target, Object value)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(Object inst, XamlMember property, Object value)
--- End of inner exception stack trace ---
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.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
What is the magical incantation to get XAML to accept a reference with a converter on a value type in lieu of Color element?
UPDATE 1
I also tried the following:
<SolidColorBrush x:Key="ButtonFaceBrush" Color="{DynamicResource ButtonFaceColor}"/>
This yields a design-time error:
An object of the type "System.Windows.Data.Binding" cannot be applied to a property that expects the type "System.Windows.Media.Color".
Which is kind of a clue to why Binding wouldn't have had worked, I guess. Changing it into:
<SolidColorBrush x:Key="ButtonFaceBrush" Color="{Binding ButtonFaceColor}"/>
dismisses the design-time error. However, actually running the application throws the same exception reported originally.

Having problems debugging and building a WPF app

I've been making modifications to a WPF app we wrote a few years ago using the ModernUI framework, adding a Shared Project, making the necessary changes. However, I've found that I can neither debug the app, nor build it. When I tried to debug the app I get this error:
System.Windows.Markup.XamlParseException
HResult=0x80131501
Message='Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' Line number '7' and line position '19'.
Source=PresentationFramework
StackTrace:
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 LRAT.MainWindow.InitializeComponent() in D:\Src\LRAT\Labor Relations Action Tracker (LRAT)\LRAT\LRAT\MainWindow.xaml:line 1
Inner Exception 1:
IOException: Cannot locate resource 'assets/14546169_s-01.ico'.
I've searching throughout the project. There were two places in a couple of ModernWindow which had that .ico file the value of the Icon property. However, I changed it to be like this:
<mui:ModernWindow x:Class="LRAT.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mui="http://firstfloorsoftware.com/ModernUI"
xmlns:view="clr-namespace:LRAT.View"
xmlns:uc="clr-namespace:LRAT.UserControls"
Style="{StaticResource BlankWindow}"
Closing="ModernWindow_Closing"
Icon="/Assets/14546169_S-01.ico"
Loaded="ModernWindow_Loaded"
>
So, I don't know where else to look, since searching through the whole solution didn't show anything like assets/14546169_s-01.ico, whereas I've changed the 2 .xaml files to be /assets/14546169_s-01.ico.
If I try to build it, the rest is even weirder. All it tells me is
Unknown build error, 'An item with the same key has already been added.'
The only thing it says is that the problem is in the LRAT project. No file is mentioned.
We started this project with VS 2017. I get the errors there. And I get them with VS 2019, too.

Devexpress thememanager routed event already used when instantiating prism view

I am building a business app based on a tiny variation of the Prism framework (couple of changes in behaviour but nothing in areas that would affect my issue.
I built a shell application, with a shell window that was created using the devexpress dxwindow wizard in vs2010. I created a region inside a devexpress layout panel for my main content. I then created a view, which also uses devexpress controls, in a separate project, that is then targeted at that region.
When the app starts and the view is registered and therefore "injected" (in the logical sense, not the DI or other programming concepts sense) into the region, I get one massive error that appears to be related to devexpress theming, but to be blunt, I don't know what the hell it's going on about. I should point out my WPF knowledge is gaining fast but still reasonably low.
Here's the details...
System.Windows.Markup.XamlParseException occurred
Message='The invocation of the constructor on type 'DevExpress.Xpf.LayoutControl.LayoutControl' that matches the specified binding constraints threw an exception.' Line number '14' and line position '10'.
Source=PresentationFramework
LineNumber=14
LinePosition=10
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 MyProject.Wpf.Modules.Partner.PartnerView.InitializeComponent() in c:\Workspace\Projects\MyProject\trunk\src\Wpf\MyProject.Wpf.Modules.Partner\PartnerView.xaml:line 1
at MyProject.Wpf.Modules.Partner.PartnerView..ctor() in C:\Workspace\Projects\MyProject\trunk\src\Wpf\MyProject.Wpf.Modules.Partner\PartnerView.xaml.cs:line 24
InnerException: System.Xaml.XamlObjectWriterException
Message=Set property 'System.Windows.ResourceDictionary.Source' threw an exception.
Source=System.Xaml
LineNumber=0
LinePosition=0
StackTrace:
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(Object inst, XamlMember property, Object value)
at MS.Internal.Xaml.Runtime.PartialTrustTolerantRuntime.SetValue(Object obj, XamlMember property, Object value)
at System.Xaml.XamlObjectWriter.SetValue(Object inst, XamlMember property, Object value)
at System.Xaml.XamlObjectWriter.Logic_ApplyPropertyValue(ObjectWriterContext ctx, XamlMember prop, Object value, Boolean onParent)
at System.Xaml.XamlObjectWriter.Logic_DoAssignmentToParentProperty(ObjectWriterContext ctx)
at System.Xaml.XamlObjectWriter.Logic_AssignProvidedValue(ObjectWriterContext ctx)
at System.Xaml.XamlObjectWriter.WriteEndMember()
at System.Xaml.XamlWriter.WriteNode(XamlReader reader)
at System.Xaml.XamlServices.Transform(XamlReader xamlReader, XamlWriter xamlWriter, Boolean closeWriter)
at System.Xaml.XamlServices.Transform(XamlReader xamlReader, XamlWriter xamlWriter)
at System.Windows.SystemResources.ResourceDictionaries.LoadDictionary(Assembly assembly, String assemblyName, String resourceName, Boolean isTraceEnabled)
at System.Windows.SystemResources.ResourceDictionaries.LoadGenericDictionary(Boolean isTraceEnabled)
at System.Windows.SystemResources.FindDictionaryResource(Object key, Type typeKey, ResourceKey resourceKey, Boolean isTraceEnabled, Boolean allowDeferredResourceReference, Boolean mustReturnDeferredResourceReference, Boolean& canCache)
at System.Windows.SystemResources.FindResourceInternal(Object key, Boolean allowDeferredResourceReference, Boolean mustReturnDeferredResourceReference)
at System.Windows.StyleHelper.GetThemeStyle(FrameworkElement fe, FrameworkContentElement fce)
at System.Windows.FrameworkElement.UpdateThemeStyleProperty()
at System.Windows.FrameworkElement.OnThemeStyleKeyChanged(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.FrameworkElement.set_DefaultStyleKey(Object value)
at DevExpress.Xpf.Core.CornerBox..ctor()
at DevExpress.Xpf.Core.PanelControllerBase.CreateScrollBars()
at DevExpress.Xpf.Core.PanelControllerBase.CheckScrollBars()
at DevExpress.Xpf.Core.Controller.set_ScrollBars(ScrollBars value)
at DevExpress.Xpf.Core.ScrollControlController..ctor(IScrollControl control)
at DevExpress.Xpf.LayoutControl.LayoutControllerBase..ctor(ILayoutControlBase control)
at DevExpress.Xpf.LayoutControl.LayoutGroupController..ctor(ILayoutGroup control)
at DevExpress.Xpf.LayoutControl.LayoutControlController..ctor(ILayoutControl control)
at DevExpress.Xpf.LayoutControl.LayoutControl.CreateController()
at DevExpress.Xpf.Core.PanelBase..ctor()
at DevExpress.Xpf.Core.ScrollControl..ctor()
at DevExpress.Xpf.LayoutControl.LayoutControlBase..ctor()
at DevExpress.Xpf.LayoutControl.LayoutGroup..ctor()
at DevExpress.Xpf.LayoutControl.LayoutControl..ctor()
at System.Xaml.Schema.XamlTypeInvoker.DefaultCtorXamlActivator.InvokeDelegate(Action`1 action, Object argument)
at System.Xaml.Schema.XamlTypeInvoker.DefaultCtorXamlActivator.CallCtorDelegate(XamlTypeInvoker type)
at System.Xaml.Schema.XamlTypeInvoker.DefaultCtorXamlActivator.CreateInstance(XamlTypeInvoker type)
at System.Xaml.Schema.XamlTypeInvoker.CreateInstance(Object[] arguments)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstanceWithCtor(XamlType xamlType, Object[] args)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstance(XamlType xamlType, Object[] args)
InnerException: System.Windows.Markup.XamlParseException
Message=Set property 'System.Windows.ResourceDictionary.DeferrableContent' threw an exception.
Source=PresentationFramework
LineNumber=0
LinePosition=0
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.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
at MS.Internal.AppModel.AppModelKnownContentFactory.BamlConverter(Stream stream, Uri baseUri, Boolean canUseTopLevelBrowser, Boolean sandboxExternalContent, Boolean allowAsync, Boolean isJournalNavigation, XamlReader& asyncObjectConverter)
at MS.Internal.AppModel.MimeObjectFactory.GetObjectAndCloseStream(Stream s, ContentType contentType, Uri baseUri, Boolean canUseTopLevelBrowser, Boolean sandboxExternalContent, Boolean allowAsync, Boolean isJournalNavigation, XamlReader& asyncObjectConverter)
at System.Windows.ResourceDictionary.set_Source(Uri value)
at System.Windows.Baml2006.WpfSharedBamlSchemaContext.<Create_BamlProperty_ResourceDictionary_Source>b__1c4(Object target, 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: System.TypeInitializationException
Message=The type initializer for 'DevExpress.Xpf.Core.ThemeManager' threw an exception.
Source=DevExpress.Xpf.Core.v10.2
TypeName=DevExpress.Xpf.Core.ThemeManager
StackTrace:
at DevExpress.Xpf.Core.ThemeManager.get_TraceSwitch()
at DevExpress.Xpf.Utils.Themes.DefaultStyleThemeKeyExtension.RegisterThemeType()
at DevExpress.Xpf.Utils.Themes.DefaultStyleThemeKeyExtension.ProvideValue(IServiceProvider serviceProvider)
at System.Windows.ResourceDictionary.EvaluateMarkupExtensionNodeList(XamlReader reader, IServiceProvider serviceProvider)
at System.Windows.ResourceDictionary.GetKeyValue(KeyRecord key, IServiceProvider serviceProvider)
at System.Windows.ResourceDictionary.SetKeys(IList`1 keyCollection, IServiceProvider serviceProvider)
at System.Windows.ResourceDictionary.SetDeferrableContent(DeferrableContent deferrableContent)
at System.Windows.Baml2006.WpfSharedBamlSchemaContext.<Create_BamlProperty_ResourceDictionary_DeferrableContent>b__168(Object target, 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: System.ArgumentException
Message=RoutedEvent Name 'ThemeChanged' for OwnerType 'System.Windows.DependencyObject' already used.
Source=PresentationCore
StackTrace:
at System.Windows.EventManager.RegisterRoutedEvent(String name, RoutingStrategy routingStrategy, Type handlerType, Type ownerType)
at DevExpress.Xpf.Core.ThemeManager..cctor()
InnerException:
The view does work in a static app, ie not using regions, and not using other devexpress controls outside the view.
Many thanks.
I had a the same error a while ago. What I found was that I had multiple versions of the controls on my PC and it was mixing versions of DevExpress controls (for me it was 11.1 and 11.2).
if you're using a DevExpress template it may be worth checking to see what version of the controls it's adding as references. if you're using a newer version of the controls then this could lead to a version mismatch.

What caused the NullReferenceException in WpfXamlLoader.TransformNodes ()?

I am trying to track down a problem that only happens in release mode and is most likely caused by the invalid obfuscation of some property. I know it happens when initializing a specific control but this control is huge. I have spent a day going through all the XAML and Bindings and still can't see what is causing this exception.
Is there any way to get more information. To know what caused this exception?
Exception : System.NullReferenceException
Message : Object reference not set to an instance of an object.
Source : PresentationFramework
Help :
Stack :
at System.Windows.Markup.WpfXamlLoader.TransformNodes(XamlReader xamlReader, XamlObjectWriter xamlWriter, Boolean onlyLoadOneNode, Boolean skipJournaledProperties, Boolean shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack`1 stack, IStyleConnector styleConnector)
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 MyClass.InitializeComponent()
I don't know a way to get a more detailed exception message, but it might at least be useful to other people to know possible causes. I've just tracked a NullReferenceException in WpfXamlLoader.TransformNodes down to a DependencyProperty which was registered with DependencyProperty.Register(string, Type, Type). Changing
public static readonly DependencyProperty FooProperty = DependencyProperty.Register(
nameof(Foo), typeof(object), typeof(Bar));
to
public static readonly DependencyProperty FooProperty = DependencyProperty.Register(
nameof(Foo), typeof(object), typeof(Bar), new FrameworkPropertyMetadata(null));
fixed the problem.
It does not seem possible to get a more detailed exception message. Dividing the problematic XAML into smaller parts is the way to go.

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

Resources