System windows markup xamlparseexception не обнаружено подходящего конструктора для типа

XamlParseException: No matching constructor found on type Today in this article, we will cover below aspects, Issue DescriptionResolution Issue Description WPF application runtime gives below error, System.Windows.Markup.XamlParseException Message='No matching constructor found on type MissingMethodException: No

Today in this article, we will cover below aspects,

  • Issue Description
  • Resolution

Issue Description

WPF application runtime gives below error,

System.Windows.Markup.XamlParseException
Message=’No matching constructor found on type MissingMethodException: No default constructor found for type ‘WPFDesktopApp.EmployeeWindow’. You can use the Arguments or FactoryMethod directives to construct this type.

XamlParseException No matching constructor found on type

Resolution

This issue is more visible when you try to provide a custom instance of the Window object.

For Example, The issue is common when the target Window is being instantiated with parameterized constructor etc.

 public partial class EmployeeWindow : Window
    {

        private readonly IEmployeeViewModel _businessObject;
        public EmployeeWindow(IEmployeeViewModel business)
        {
            InitializeComponent();
            _businessObject = business;

        }
...

   }

In such cases, please remove default StartupUri property being set in the App.xaml file.

No matching constructor found on type

The issue resolves once the above line is removed.

  • Reference: Dependency Injection in WPF application in .NET Core

Did I miss anything else in these resolution steps?

Did the above steps resolve your issue? Please sound off your comments below!

Happy Coding !!


Please bookmark this page and share it with your friends. Please Subscribe to the blog to get a notification on freshly published best practices and guidelines for software design and development.


21.03.2011, 07:24. Показов 27626. Ответов 16


Работал работал с проектом и вылезла вот такая ошибка :System.Windows.Markup.XamlParseException не обработано

Текст исключения

Message=»Вызов конструктора для типа «Wpf_3_PressADay.MainWindow», удовлетворяющего указанным ограничениям привязки, привел к выдаче исключения.»: номер строки «3» и позиция в строке «9».
Source=PresentationFramework
LineNumber=3
LinePosition=9
StackTrace:
в System.Windows.Markup.XamlReader.RewrapException(E xception e, IXamlLineInfo lineInfo, Uri baseUri)
в System.Windows.Markup.WpfXamlLoader.Load(XamlReade r xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
в System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlR eader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
в System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
в System.Windows.Application.LoadBamlStreamWithSyncI nfo(Stream stream, ParserContext pc)
в System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
в System.Windows.Application.DoStartup()
в System.Windows.Application.<.ctor>b__1(Object unused)
в System.Windows.Threading.ExceptionWrapper.Internal RealCall(Delegate callback, Object args, Int32 numArgs)
в MS.Internal.Threading.ExceptionFilterHelper.TryCat chWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
в System.Windows.Threading.DispatcherOperation.Invok eImpl()
в System.Windows.Threading.DispatcherOperation.Invok eInSecurityContext(Object state)
в System.Threading.ExecutionContext.runTryCode(Objec t userData)
в System.Runtime.CompilerServices.RuntimeHelpers.Exe cuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
в System.Threading.ExecutionContext.RunInternal(Exec utionContext executionContext, ContextCallback callback, Object state)
в System.Threading.ExecutionContext.Run(ExecutionCon text executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
в System.Threading.ExecutionContext.Run(ExecutionCon text executionContext, ContextCallback callback, Object state)
в System.Windows.Threading.DispatcherOperation.Invok e()
в System.Windows.Threading.Dispatcher.ProcessQueue()
в System.Windows.Threading.Dispatcher.WndProcHook(In tPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
в MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
в MS.Win32.HwndSubclass.DispatcherCallbackOperation( Object o)
в System.Windows.Threading.ExceptionWrapper.Internal RealCall(Delegate callback, Object args, Int32 numArgs)
в MS.Internal.Threading.ExceptionFilterHelper.TryCat chWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
в System.Windows.Threading.Dispatcher.InvokeImpl(Dis patcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
в MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
в MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
в System.Windows.Threading.Dispatcher.PushFrameImpl( DispatcherFrame frame)
в System.Windows.Threading.Dispatcher.PushFrame(Disp atcherFrame frame)
в System.Windows.Threading.Dispatcher.Run()
в System.Windows.Application.RunDispatcher(Object ignore)
в System.Windows.Application.RunInternal(Window window)
в System.Windows.Application.Run(Window window)
в System.Windows.Application.Run()
в Wpf_3_PressADay.App.Main() в C:UsersВладимирDesktopWpf_3_PressADayWpf_3_Pr essADayobjx86DebugApp.g.cs:строка 0
в System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
в System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
в Microsoft.VisualStudio.HostingProcess.HostProc.Run UsersAssembly()
в System.Threading.ThreadHelper.ThreadStart_Context( Object state)
в System.Threading.ExecutionContext.Run(ExecutionCon text executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
в System.Threading.ExecutionContext.Run(ExecutionCon text executionContext, ContextCallback callback, Object state)
в System.Threading.ThreadHelper.ThreadStart()
InnerException: System.IO.IOException
Message=Не удается найти ресурс «c».
Source=PresentationFramework
StackTrace:
в MS.Internal.AppModel.ResourcePart.GetStreamCore(Fi leMode mode, FileAccess access)
в System.IO.Packaging.PackagePart.GetStream(FileMode mode, FileAccess access)
в System.IO.Packaging.PackagePart.GetStream()
в System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
в Wpf_3_PressADay.MainWindow.InitializeComponent() в c:UsersВладимирDesktopWpf_3_PressADayWpf_3_Pr essADayMainWindow.xaml:строка 1
в Wpf_3_PressADay.MainWindow..ctor() в C:UsersВладимирDesktopWpf_3_PressADayWpf_3_Pr essADayMainWindow.xaml.cs:строка 36
InnerException:

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



I have written a WPF application, on my compuyter it is running ok.
Now I am trying to deploy wpf application on W7 computer. And getting following exception:

Description: The process was terminated due to an unhandled exception.
Exception Info: System.Windows.Markup.XamlParseException
Stack:
   at System.Windows.Markup.XamlReader.RewrapException(System.Exception, System.Xaml.IXamlLineInfo, System.Uri)
   at System.Windows.Markup.WpfXamlLoader.Load(System.Xaml.XamlReader, System.Xaml.IXamlObjectWriterFactory, Boolean, System.Object, System.Xaml.XamlObjectWriterSettings, System.Uri)
   at System.Windows.Markup.WpfXamlLoader.LoadBaml(System.Xaml.XamlReader, Boolean, System.Object, System.Xaml.Permissions.XamlAccessLevel, System.Uri)
   at System.Windows.Markup.XamlReader.LoadBaml(System.IO.Stream, System.Windows.Markup.ParserContext, System.Object, Boolean)
   at System.Windows.Application.LoadBamlStreamWithSyncInfo(System.IO.Stream, System.Windows.Markup.ParserContext)
   at System.Windows.Application.LoadComponent(System.Uri, Boolean)
   at System.Windows.Application.DoStartup()
   at System.Windows.Application.<.ctor>b__1(System.Object)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate, System.Object, Int32)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(System.Object, System.Delegate, System.Object, Int32, System.Delegate)
   at System.Windows.Threading.DispatcherOperation.InvokeImpl()
   at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(System.Object)
   at System.Threading.ExecutionContext.runTryCode(System.Object)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode, CleanupCode, System.Object)
   at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.ProcessQueue()
   at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef)
   at MS.Win32.HwndWrapper.WndProc(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(System.Object)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate, System.Object, Int32)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(System.Object, System.Delegate, System.Object, Int32, System.Delegate)
   at System.Windows.Threading.Dispatcher.InvokeImpl(System.Windows.Threading.DispatcherPriority, System.TimeSpan, System.Delegate, System.Object, Int32)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr, Int32, IntPtr, IntPtr)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(System.Windows.Interop.MSG ByRef)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame)
   at System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame)
   at System.Windows.Threading.Dispatcher.Run()
   at System.Windows.Application.RunDispatcher(System.Object)
   at System.Windows.Application.RunInternal(System.Windows.Window)
   at System.Windows.Application.Run(System.Windows.Window)
   at System.Windows.Application.Run()
   at CAMXSimulator.App.Main()

Any idea what is wrong here ?

Thanks

Sprite

Фотография

Дата: 08.10.2021

Ответить

Юрий, добрый день!

Ошибка XAML больше не показывается, приложение SampleConnection запустилось.
И выдало новую ошибку

SampleConnection 08.10.2021 20:32:56 +03:00 Error System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
—> System.TypeInitializationException: The type initializer for ‘#=zKZ3pQfy60PBJ9KEnUCXz6fO4P6ux35H6xQ==’ threw an exception.
—> System.MissingMethodException: Method not found: ‘System.String StockSharp.Localization.LocalizedStrings.get_WshMeta()’.
at #=zKZ3pQfy60PBJ9KEnUCXz6fO4P6ux35H6xQ==..cctor()
— End of inner exception stack trace —
at StockSharp.InteractiveBrokers.InteractiveBrokersMessageAdapter..ctor(IdGenerator transactionIdGenerator)
— End of inner exception stack trace —
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, Object[] args)
at Ecng.Common.TypeHelper.CreateInstance[T](Type type, Object[] args)
at StockSharp.Messages.Extensions.CreateAdapter(Type adapterType, IdGenerator idGenerator) in C:TempS#StockSharp-masterMessagesExtensions.cs:line 1534
at StockSharp.Configuration.InMemoryMessageAdapterProvider.<>c__DisplayClass0_0.<.ctor>b__0(Type t) in C:TempS#StockSharp-masterConfigurationInMemoryMessageAdapterProvider.cs:line 35

Затем, после настройки коннектора и соединения в SampleConnection портфели пустые. Т.е. нажав на кнопку «Портфель» мы ничего не видим.
А мое приложение при попытке синхронизировать портфели выдает вот такую ошибку:

Application 08.10.2021 20:57:08 +03:00 Error System.InvalidOperationException: Сообщение ‘PositionChange,T(L)=2021/09/24 21:25:30.000,Offline=Ignore,T(S)=2021/10/08 20:57:01.061,Sec=MONEY@ALL,P=1NGKE/1NGKE,CL=,L=,Changes=[BeginValue, XXXXXXXXX],[CurrentValue, XXXXXXXXX]’ привело к ошибке обработки.
—> System.MissingMethodException: Method not found: ‘StockSharp.Messages.SecurityId StockSharp.Messages.Extensions.ToSecurityId(System.String, StockSharp.Messages.SecurityIdGenerator)’.
at #=zgC1u2niVVYTPQl8i0w==..ctor(Position #=z2Frq3yQ=, Action`1 #=ziNvQbGQ=)
at StockSharp.Xaml.PortfolioGrid.#=z552NRg8=.#=zxpyx$pkufkgJqrTUyw==(Position #=zl$8T$Qw=, Action`1 #=z8L0bGMU=)
at #=zt0X6pcolWad5Eif5fiQbzAzhnX09zG47FGBN3rw=.#=z_AuS7y3_Ua7RpCSiGw==.#=zUv0r35RICvoqPZxAWw==(#=zumWTMD0= #=zVetCjME=)
at #=zqa7rTY84WF9I6UPsH_RHNoo=.Add(#=zYKYUK9Y= #=z37A1PzY=)
at Ecng.Collections.CollectionHelper.<TryAdd>g__InternalTryAdd|12_0[T](<>c__DisplayClass12_0`1& )
at Ecng.Collections.CollectionHelper.TryAdd[T](ICollection`1 collection, T value)
at Algo.Application.MainWindow.<AttachConnectorEvents>b__17_5(Subscription s, Position position) in C:TempS#RobotsAlgo.ApplicationMainWindow.xaml.cs:line 460
at StockSharp.Algo.Connector.RaiseReceived[TEntity](TEntity entity, IEnumerable`1 subscriptions, Action`2 evt, Nullable`1& anyCanOnline) in C:TempS#StockSharp-masterAlgoConnector_Raise.cs:line 973
at StockSharp.Algo.Connector.RaiseReceived[TEntity](TEntity entity, ISubscriptionIdMessage message, Action`2 evt, Nullable`1& anyCanOnline) in C:TempS#StockSharp-masterAlgoConnector_Raise.cs:line 948
at StockSharp.Algo.Connector.RaiseReceived[TEntity](TEntity entity, ISubscriptionIdMessage message, Action`2 evt) in C:TempS#StockSharp-masterAlgoConnector_Raise.cs:line 943
at StockSharp.Algo.Connector.ProcessPositionChangeMessage(PositionChangeMessage message) in C:TempS#StockSharp-masterAlgoConnector_ProcessMessage.cs:line 1103
at StockSharp.Algo.Connector.OnProcessMessage(Message message) in C:TempS#StockSharp-masterAlgoConnector_ProcessMessage.cs:line 642
— End of inner exception stack trace —

А при попытке посмотреть стакан по какому-нибудь инструменту SampleConnection выдает вот такую ошибку:

System.Windows.Markup.XamlParseException: ‘»Не обнаружено подходящего конструктора для типа «StockSharp.Xaml.MarketDepthControl». Можно использовать директивы Arguments или FactoryMethod для формирования этого типа.»: номер строки «6» и позиция в строке «3».’
InnerException
MissingMethodException: Method not found: ‘StockSharp.Messages.Sides StockSharp.Messages.Extensions.Invert(StockSharp.Messages.Sides)’.

Стек:
System.Windows.Markup.XamlParseException: «Не обнаружено подходящего конструктора для типа «StockSharp.Xaml.MarketDepthControl». Можно использовать директивы Arguments или FactoryMethod для формирования этого типа.»: номер строки «6» и позиция в строке «3».
—> System.MissingMethodException: Method not found: ‘StockSharp.Messages.Sides StockSharp.Messages.Extensions.Invert(StockSharp.Messages.Sides)’.
at StockSharp.Xaml.MarketDepthControl.#=zxDcwRhtyWNkY(Int32 #=zzahPLws=)
at StockSharp.Xaml.MarketDepthControl..ctor()
at MarketDepthControlCtor(Object[] )
at MS.Internal.Xaml.Runtime.DynamicMethodRuntime.CreateInstanceWithCtor(Type type, Object[] args)
at MS.Internal.Xaml.Runtime.DynamicMethodRuntime.CreateInstanceWithCtor(XamlType xamlType, Object[] args)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstance(XamlType xamlType, Object[] args)
— 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.LoadComponent(Object component, Uri resourceLocator)
at SampleConnection.QuotesWindow.InitializeComponent() in C:TempS#StockSharp-masterSamplesConnectorsSampleConnectionQuotesWindow.xaml:line 1
at SampleConnection.QuotesWindow..ctor() in C:TempS#StockSharp-masterSamplesConnectorsSampleConnectionQuotesWindow.xaml.cs:line 16
at SampleConnection.SecuritiesWindow.SubscribeDepths(DepthSettings settings) in C:TempS#StockSharp-masterSamplesConnectorsSampleConnectionSecuritiesWindow.xaml.cs:line 313
at SampleConnection.SecuritiesWindow.DepthClick(Object sender, RoutedEventArgs e) in C:TempS#StockSharp-masterSamplesConnectorsSampleConnectionSecuritiesWindow.xaml.cs:line 245
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
at System.Windows.Controls.Primitives.ButtonBase.OnClick()
at System.Windows.Controls.Button.OnClick()
at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)

image4897.png

WPF TextBox XamlParseException when culture is «ru-RU» (.NET Core 3.0.0 Preview 6)

Empty netcore wpf project and window with textbox

    public MainWindow()
    {
         InitializeComponent(); // System.Windows.Markup.XamlParseException
    }
    <Window
        x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:local="clr-namespace:WpfApp1"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Title="MainWindow"
        Width="800"
        Height="450"
        mc:Ignorable="d">
        <TextBox />
    </Window>

Exception details (localized (ru))

    System.Windows.Markup.XamlParseException
      HResult=0x80131501
      Message="Вызов конструктора для типа "System.Windows.Controls.TextBox", удовлетворяющего указанным ограничениям привязки, привел к выдаче исключения.": номер строки "13" и позиция в строке "10".
      Source=PresentationFramework
      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 WpfApp1.MainWindow.InitializeComponent() in F:devtestWpfApp1WpfApp1MainWindow.xaml:line 1

    Inner Exception 1:
    ArgumentException: Requested value 'УДАЛИТЬ' was not found.

but it works with en-US culture

    public MainWindow()
    {
        Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-us");
        InitializeComponent();
    }

ps: .NET Core 3.0.0 Preview 5 — everything works well

  • Remove From My Forums
  • Question

  • I can run my WPF application.exe file locally fine, however if I copy the executable to another machine I get a Windows report error dialog. The only useful error info I see is:

    system.windows.markup.xamlparse

    I am including the referenced dlls. Is there anything else that could cause this?

Answers

  • It is more then likely a problem with your xaml that is only discovered at runtime.  For example if you you reference a static resource that doesn’t exist, you will get the exception you mentioned.  Here would be an example of offending code, because
    MissStyle does not exist.

    <TextBlock Style=»{StaticResource MissingStyle}»/>

    To find out what the exact problem is  you may have to set up the IDE to break on WPF exceptions:
    –Open the «Exceptions» window (Debug/Exceptions) in Visual Studio.
    –Click “Add»
    — Set Type to “Common Language Runtime Exceptions”
    — Set Name to “System.Windows.Markup.XamlParseException”
    — Hit “OK”
    — Check the box to “Break on Thrown”

    Run the app again and it should break on the line that has the issue.

    • Marked as answer by

      Friday, April 1, 2011 8:43 PM

There is an exception which many people hit when first creating dependency properties.

System.Windows.Markup.XamlParseException: The invocation of the constructor on type ‘[type name here]’ that matches the specified binding constraints threw an exception.

Don’t worry – it’s very easy to fix and also very commonly made.

You first dependency property may look something like this, especially if you use the code snippet “propdp“.

        public long MyProperty
        {
            get { return (long)GetValue(MyPropertyProperty); }
            set { SetValue(MyPropertyProperty, value); }
        }

        public static readonly DependencyProperty MyPropertyProperty =
            DependencyProperty.Register(
                "MyProperty",
                typeof(long),
                typeof(MyClass),
                new PropertyMetadata(0));

If you created your code using the code snippet it will compile just fine and the world will be a happy place. The problem lies in the constructor of the PropertyMetadata on line 12 above where you set the default value for the property.

The definition of the constructor is:

public PropertyMetadata(object defaultValue);

The type of the parameter ‘defaultValue‘ is ‘object‘, this means that your default value will be boxed as an object type.

The error comes when the default value is needed and is unboxed. If you didn’t carefully force the type of the value going in then the most sensible type will be chosen by the compiler, which may differ from the type you specified on line 10, i.e. the underlying type you wish to use for your dependency property.

Using the above as an example, the default value is set to ‘0‘ – the compiler will interpret ‘0‘ to be an Int32 and then the constructor will store that Int32 typed value as the default value in the defaultValue object.

When you come to need the default value the code that is executed behind the scenes will attempt to turn your default value back to the type specified for your dependency property, i.e.

long value = (long)defaultValue;

Much to many people’s surprise, this is not possible and will throw the exception above. Why? Well, you need to unbox back to the underlying type before you cast it to another type.

Take the following code, which you can paste into a console project to check out:

var myInt = 0;
Console.WriteLine(myInt.GetType().Name); // produces Int32

object myObj = myInt;
Console.WriteLine(myObj.GetType().Name); // produces Int32 - the underlying type

// no problem
long myLong1 = (long)myInt;

// no problem - unboxing to int and then casting to long
long myLong2 = (long)(int)myObj;

// exception - can't unbox to a different type
long myLong3 = (long)myObj;

Note that on line 1 I declared the variable using var instead of int, however we can still see that the compiler has decided that Int32 is the best way to go with this value.

So, back to the exception, and how to correct it. Simple really, make sure that the compiler is aware of the type of value that you are passing in and make sure that it matches the type you are declaring for your dependency property.

In the example above we only need to replace line 12 with the following using an explicit cast.

                new PropertyMetadata((long)0));

Alternatively we could have used a type suffixes as a shortcut.

 new PropertyMetadata(0l));

Other type suffices are:
u – uint
l – long
ul – ulong
f – float
d – double
m – decimal

If you are interested in a more depth article on boxing and unboxing and casting in general, see Eric Lippert’s excellent blog post.

Понравилась статья? Поделить с друзьями:
  • System windows markup xamlparseexception задание значения connectionid вызвало исключение
  • System windows forms screen primaryscreen bounds
  • System windows forms messagebox system windows forms messagebox
  • System windows forms dll где находится
  • System windows forms datavisualization charting как подключить