Создал проект на WPF и закинул на него пару кнопок и началась магия, по другому я не могу сказать.
Запускаю проект на F5 и пытаюсь развернуть форму - получаю ошибку System.ArgumentException: "API-функция вызвана с аргументами из неправильного контекста."
Никаких потоков у меня нет. Проект, можно сказать, чистый, на окне только 2 кнопки и ничего больше.
Если запускать проект на Ctrl+f5 - всё прекрасно работает и ничего не вылетает и не крашится.
С чем это может быть связано?
Использую библиотеки: prism, propertychanged.fody, devexpress.mvvm.
А если еще добавить DataGrid
, то вылетает сразу после появления окна.
p.s. - если убрать viewmodel, то никаких проблем нет. Но в чем проблема с ней? Там просто инициализация ObservableCollection
(просто new ...).
Подробности ошибки:
System.ArgumentException
HResult=0x80070057
Сообщение = API-функция вызвана с аргументами из неправильного контекста.
Источник = PresentationCore
Трассировка стека:
at System.Windows.Media.MediaSystem.AssertSameContext(DispatcherObject reference, DispatcherObject other)
at System.Windows.Media.Visual.set_VisualTransform(Transform value)
at System.Windows.Media.ContainerVisual.set_Transform(Transform value)
at System.Windows.Controls.Viewbox.ArrangeOverride(Size arrangeSize)
at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
at System.Windows.UIElement.Arrange(Rect finalRect)
at System.Windows.Controls.Control.ArrangeOverride(Size arrangeBounds)
at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
at System.Windows.UIElement.Arrange(Rect finalRect)
at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize)
at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
at System.Windows.UIElement.Arrange(Rect finalRect)
at System.Windows.Controls.Border.ArrangeOverride(Size finalSize)
at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
at System.Windows.UIElement.Arrange(Rect finalRect)
at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize)
at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
at System.Windows.UIElement.Arrange(Rect finalRect)
at System.Windows.Controls.Control.ArrangeOverride(Size arrangeBounds)
at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect)
at System.Windows.UIElement.Arrange(Rect finalRect)
at System.Windows.ContextLayoutManager.UpdateLayout()
at System.Windows.ContextLayoutManager.UpdateLayoutCallback(Object arg)
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 System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
at MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(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)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run()
at FoldersWatcher.App.Main()
Изначально это исключение было создано в этом стеке вызовов:
[Внешний код]
Разметка окна:
<Window x:Class="FoldersWatcher.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:FoldersWatcher.ViewModels"
Style="{StaticResource MaterialDesignWindow}"
mc:Ignorable="d"
Title="Folders Watcher"
Height="450"
Width="800"
d:DataContext="{d:DesignInstance Type=vm:MainWindowViewModel, IsDesignTimeCreatable=True}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<GroupBox Header="Папки для слежения"
Margin="5">
<StackPanel>
<Button Content="Добавить папку"
Command="{Binding AddFolderCommand}"
Style="{StaticResource MaterialDesignFlatButton}"
Margin="5"/>
<Button Content="Удалить выбранную папку"
Style="{StaticResource MaterialDesignFlatButton}"
Margin="5"/>
<ListBox ItemsSource="{Binding Folders}"
SelectedItem="{Binding SelectedFolder}"
Margin="5"/>
</StackPanel>
</GroupBox>
<GroupBox Header="Файлы"
Grid.Column="1"
Margin="5">
<DataGrid ItemsSource="{Binding Files}"/>
</GroupBox>
</Grid>
</Window>
ViewModel:
public class MainWindowViewModel : ViewModelBase
{
/// <summary>
/// Папки для слежения.
/// </summary>
public ObservableCollection<string> Folders { get; }
/// <summary>
/// Файлы, которые были созданы.
/// </summary>
public ObservableCollection<FileModel> Files { get; }
/// <summary>
/// Выбранная папка.
/// </summary>
public string SelectedFolder { get; set; }
/// <summary>
/// Надблюдатели за папками.
/// </summary>
private readonly Dictionary<string, FileSystemWatcher> watchers;
/// <summary>
/// Notification manager.
/// </summary>
private readonly INotificationManager notificationManager;
/// <summary>
/// Sync.
/// </summary>
private readonly TaskFactory sync;
/// <summary>
/// Конструктор.
/// </summary>
public MainWindowViewModel()
{
}
/// <summary>
/// Конструктор.
/// </summary>
public MainWindowViewModel(INotificationManager notificationManager, TaskFactory sync)
{
this.notificationManager = notificationManager;
this.sync = sync;
Folders = new ObservableCollection<string>();
Files = new ObservableCollection<FileModel>();
watchers = new Dictionary<string, FileSystemWatcher>();
AddFolderCommand = new DelegateCommand(AddFolder);
}
/// <summary>
/// Команда добавления новой папки для слежения.
/// </summary>
public ICommand AddFolderCommand { get; }
/// <summary>
/// Добавить папку для слежения.
/// </summary>
private void AddFolder()
{
}
}
App.cs
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : PrismApplication
{
/// <summary>
/// View -> ViewModel.
/// </summary>
protected override void ConfigureViewModelLocator()
{
ViewModelLocationProvider.Register<MainWindow, MainWindowViewModel>();
base.ConfigureViewModelLocator();
}
/// <summary>
/// Создание окна.
/// </summary>
/// <returns></returns>
protected override Window CreateShell()
{
return Container.Resolve<MainWindow>();
}
/// <summary>
/// Регистрация зависимостей.
/// </summary>
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterDelegate<TaskFactory>(x => new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext()), Reuse.Singleton);
containerRegistry.RegisterSingleton<INotificationManager, NotificationManager>();
}
}
static class ContainerHelper
{
public static void RegisterDelegate<T>(this IContainerRegistry containerRegistry, Func<IResolverContext, T> func, IReuse reuse, string key = null)
{
containerRegistry.GetContainer().RegisterDelegate<T>(func, reuse, serviceKey: key);
}
}