DatePicker выбрасывает исключение при изменении месяца

Изменение месяца DatePicker вызывает это исключение:

System.Windows.Automation.ElementNotAvailableException: "Элемент не существует или виртуализирован; используйте шаблон VirtualizedItem, если он поддерживается.

Трассировка стека:

в MS.Internal.Automation.ElementUtil.Invoke(автоответчик AutomationPeer, DispatcherOperationCallback work, Object arg) at MS.Internal.Automation.ElementProxy.GetPropertyValue(свойство Int32)

Я создал простой проект с одним DatePicker в главном окне, и он дает то же исключение.

<DatePicker x:Name="datePicker1" Width="150" />

Версия .NET Framework: 4.6

Я нашел ту же проблему в 6-летнем вопросе, но ответа до сих пор не было!

Edit

Я пробовал разные версии .NET Framework: 4.5, 4.6.1, и проблема осталась прежней.

Ответы

Ответ 1

Если вы посмотрите в документации по Microsoft, в нем говорится:

Это исключение можно повысить, если элемент находился в закрытом диалоговом окне или приложении, которое было закрыто или завершено.

Возможно ли, что вы закрываете окно в событии "change month"?

Ответ 2

Трудно воспроизвести вашу проблему. Следующие предложения могут вам помочь:

  • другой процесс может повлиять на вашу программу. Используете ли вы утилиты типа Snoop или UISpy?

  • ваша проблема может быть связана с ошибкой программного обеспечения с низкой производительностью или программным обеспечением поставщика. См. здесь ответ для решения этой проблемы.

  • Ваша проблема может быть связана с предоставлением копии пользовательского интерфейса, который по некоторым причинам не существует. Подробнее см. обсуждение

Ответ 3

Исключение, по-видимому, зависит от включенной службы ввода Tablet PC Input. Если бы я должен был догадаться, ошибка возникает в коде UI Automation, который работает только тогда, когда доступен вход на основе пера (и, возможно, сенсорный вход). Я видел, что эта служба вызывала нежелательные побочные эффекты в приложениях WPF раньше, и большинство из этих проблем были также связаны с автоматизацией пользовательского интерфейса.

Поскольку это, по-видимому, исключение "первого шанса" (оно обрабатывается где-то в рамках), единственными людьми, которые должны заметить, являются разработчики, у которых их IDE настроен на разрыв во всех исключениях (в отличие от только необработанных исключений), Если это действительно так, и если эти разработчики фактически не используют возможности ручного или сенсорного ввода, было бы проще всего отключить службу ввода Tablet PC и продолжить свою жизнь.

В качестве альтернативы вы можете настроить Visual Studio на то, чтобы не разбивать этот тип исключения, который в любом случае относится только к автоматизации пользовательского интерфейса.

Так как на этой неделе в офисе довольно медленно, я потрачу некоторое дополнительное время на изучение этого. Если я смогу найти решение на основе кода, я обновлю свой ответ здесь. Но по внешнему виду пользовательский интерфейс построен почти полностью программно, поэтому, вероятно, это не то, что вы можете исправить с помощью простого настраиваемого шаблона.

Ответ 4

(Поскольку мне нужно было немного утечки), я попытался провести некоторое исследование по вашему делу и воспроизвести упомянутое исключение. Включение степпинга источника .NET Framework и все, что я мог найти, я смог определить исключение для метода Invoke класса ElementUtil в PresentationCore.dll. соответствующий код метода выглядит следующим образом:

internal static object Invoke(AutomationPeer peer, DispatcherOperationCallback work, object arg)
{
    Dispatcher dispatcher = peer.Dispatcher;

    // Null dispatcher likely means the visual is in bad shape!
    if( dispatcher == null )
    {
        throw new ElementNotAvailableException();
    }

    Exception remoteException = null;
    bool completed = false;

    object retVal = dispatcher.Invoke(            
        DispatcherPriority.Send,
        TimeSpan.FromMinutes(3),
        (DispatcherOperationCallback) delegate(object unused)
        {
            try
            {
                return work(arg);
            }
            catch(Exception e)
            {
                remoteException = e;
                return null;
            }
            catch        //for non-CLS Compliant exceptions
            {
                remoteException = null;
                return null;
            }
            finally
            {
                completed = true;
            }

        },
        null);

    if(completed)
    {
        if(remoteException != null)
        {
            throw remoteException;
        }
    }
    else
    {
        bool dispatcherInShutdown = dispatcher.HasShutdownStarted;

        if(dispatcherInShutdown)
        {
            throw new InvalidOperationException(SR.Get(SRID.AutomationDispatcherShutdown));
        }
        else
        {
            throw new TimeoutException(SR.Get(SRID.AutomationTimeout));
        }
    }

    return retVal;

}

Принимая во внимание этот код (по моему мнению), только возможная причина заключается в том, что указанный диспетчер null. Хотя я нахожу комментарий

//Неверный диспетчер, вероятно, означает, что визуал находится в плохом состоянии!

смешно, я действительно понятия не имею, почему это так. Я устал отлаживать этот факт, но не смог получить какую-либо значимую информацию. Только следующий stacktrace (который снова открыл мои глаза о том, что происходит, если мы просто нажимаем кнопку):

PresentationCore.dll!MS.Internal.Automation.ElementUtil.Invoke(System.Windows.Automation.Peers.AutomationPeer peer, System.Windows.Threading.DispatcherOperationCallback work, object arg)
PresentationCore.dll!MS.Internal.Automation.ElementProxy.GetPropertyValue(int property)
[Native to Managed Transition]
UIAutomationCore.dll!ProviderCallouts::RawGetPropertyValue(struct IRawElementProviderSimple *,int,struct tagVARIANT *)
UIAutomationCore.dll!ProviderCallouts::GetPropertyValue(struct IRawElementProviderSimple *,unsigned short,class ProviderEntryPoint *,int,struct tagVARIANT *)
UIAutomationCore.dll!InProcClientAPIStub::GetPropertyValue(char *)
UIAutomationCore.dll!InProcClientAPIStub::InvokeInProcAPI(struct ITargetContextInvoker *,enum Protocol_MethodId,...)
UIAutomationCore.dll!AccessibleProxy::IsControl(struct IRawElementProviderFragment *,struct ITargetContextInvoker *)
UIAutomationCore.dll!AccessibleProxy::NormalizeUpwards(struct IRawElementProviderFragment *,struct ITargetContextInvoker *,struct IRawElementProviderFragment * *)
UIAutomationCore.dll![thunk]:EditProxy::Release`adjustor{32}' (void)
[email protected]()
[Managed to Native Transition]
UIAutomationProvider.dll!MS.Internal.Automation.UiaCoreProviderApi.UiaReturnRawElementProvider(System.IntPtr hwnd = 0x000406ce, System.IntPtr wParam = 0xffffffff, System.IntPtr lParam = 0x00000149, System.Windows.Automation.Provider.IRawElementProviderSimple el = {MS.Internal.Automation.ElementProxy})
UIAutomationProvider.dll!System.Windows.Automation.Provider.AutomationInteropProvider.ReturnRawElementProvider(System.IntPtr hwnd = 0x000406ce, System.IntPtr wParam = 0xffffffff, System.IntPtr lParam = 0x00000149, System.Windows.Automation.Provider.IRawElementProviderSimple el = {MS.Internal.Automation.ElementProxy})
PresentationCore.dll!System.Windows.Interop.HwndTarget.CriticalHandleWMGetobject(System.IntPtr wparam, System.IntPtr lparam, System.Windows.Media.Visual root, System.IntPtr handle)
PresentationCore.dll!System.Windows.Interop.HwndTarget.HandleMessage(MS.Internal.Interop.WindowMessage msg, System.IntPtr wparam, System.IntPtr lparam)
PresentationCore.dll!System.Windows.Interop.HwndSource.HwndTargetFilterMessage(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled = false)
WindowsBase.dll!MS.Win32.HwndWrapper.WndProc(System.IntPtr hwnd = 0x000406ce, int msg = 0x0000003d, System.IntPtr wParam = 0xffffffff, System.IntPtr lParam = 0x00000149, ref bool handled = false)
WindowsBase.dll!MS.Win32.HwndSubclass.DispatcherCallbackOperation(object o)
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs)
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(object source = {System.Windows.Threading.Dispatcher}, System.Delegate callback, object args, int numArgs, System.Delegate catchHandler = null)
WindowsBase.dll!System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority priority, System.TimeSpan timeout, System.Delegate method, object args, int numArgs)
WindowsBase.dll!MS.Win32.HwndSubclass.SubclassWndProc(System.IntPtr hwnd = 0x000406ce, int msg = 0x0000003d, System.IntPtr wParam = 0xffffffff, System.IntPtr lParam = 0x00000149)
[Native to Managed Transition]
[email protected]()
user32.dll!InternalCallWinProc()
user32.dll!UserCallWinProcCheckWow(struct _ACTIVATION_CONTEXT *,void *,struct HWND__ *,enum _WM_VALUE,unsigned int,long,void *,int)
[email protected]()
[email protected]()
[email protected]()
[email protected]()
oleacc.dll!NativeIAccessibleFromWindow(unsigned long,unsigned long,struct HWND__ *,unsigned long,struct _GUID const &,void * *)
[email protected]()
[email protected]()
[email protected]()
[email protected]()
[email protected]()
msctf.dll!CThreadInputMgr::OnAccFocusEvent()
msctf.dll!WinEventProc()
[email protected]()
[email protected]()
[Managed to Native Transition]
UIAutomationProvider.dll!MS.Internal.Automation.UiaCoreProviderApi.UiaRaiseAutomationEvent(System.Windows.Automation.Provider.IRawElementProviderSimple provider = {MS.Internal.Automation.ElementProxy}, int eventId = 0x00004e25)
UIAutomationProvider.dll!System.Windows.Automation.Provider.AutomationInteropProvider.RaiseAutomationEvent(System.Windows.Automation.AutomationEvent eventId = {System.Windows.Automation.AutomationEvent}, System.Windows.Automation.Provider.IRawElementProviderSimple provider = {MS.Internal.Automation.ElementProxy}, System.Windows.Automation.AutomationEventArgs e = {System.Windows.Automation.AutomationEventArgs})
PresentationCore.dll!System.Windows.Automation.Peers.AutomationPeer.RaiseAutomationEvent(System.Windows.Automation.Peers.AutomationEvents eventId)
PresentationCore.dll!System.Windows.Automation.Peers.AutomationPeer.RaiseFocusChangedEventHelper(System.Windows.IInputElement newFocus)
PresentationCore.dll!System.Windows.Input.KeyboardDevice.ChangeFocus(System.Windows.DependencyObject focus, int timestamp)
PresentationCore.dll!System.Windows.Input.KeyboardDevice.TryChangeFocus(System.Windows.DependencyObject newFocus, System.Windows.Input.IKeyboardInputProvider keyboardInputProvider, bool askOld, bool askNew, bool forceToNullIfFailed)
PresentationCore.dll!System.Windows.Input.KeyboardDevice.Focus(System.Windows.DependencyObject focus, bool askOld, bool askNew, bool forceToNullIfFailed)
PresentationCore.dll!System.Windows.Input.KeyboardDevice.Focus(System.Windows.IInputElement element)
PresentationCore.dll!System.Windows.UIElement.Focus()
PresentationFramework.dll!System.Windows.Input.KeyboardNavigation.Navigate(System.Windows.DependencyObject currentElement, System.Windows.Input.TraversalRequest request, System.Windows.Input.ModifierKeys modifierKeys, System.Windows.DependencyObject firstElement)
PresentationFramework.dll!System.Windows.FrameworkElement.MoveFocus(System.Windows.Input.TraversalRequest request)
PresentationFramework.dll!System.Windows.Controls.Primitives.CalendarItem.FocusDate(System.DateTime date)
PresentationFramework.dll!System.Windows.Controls.Calendar.OnCalendarButtonPressed(System.Windows.Controls.Primitives.CalendarButton b, bool switchDisplayMode)
PresentationFramework.dll!System.Windows.Controls.Primitives.CalendarItem.Month_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
PresentationCore.dll!System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(System.Delegate genericHandler, object genericTarget)
PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target)
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs)
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source = {System.Windows.Controls.Primitives.CalendarButton}, System.Windows.RoutedEventArgs args = {System.Windows.Input.MouseButtonEventArgs}, bool reRaised = true)
PresentationCore.dll!System.Windows.UIElement.ReRaiseEventAs(System.Windows.DependencyObject sender = {System.Windows.Controls.Primitives.CalendarButton}, System.Windows.RoutedEventArgs args = {System.Windows.Input.MouseButtonEventArgs}, System.Windows.RoutedEvent newEvent)
PresentationCore.dll!System.Windows.UIElement.OnMouseUpThunk(object sender, System.Windows.Input.MouseButtonEventArgs e)
PresentationCore.dll!System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(System.Delegate genericHandler, object genericTarget)
PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target)
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs)
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source = {System.Windows.Shapes.Rectangle}, System.Windows.RoutedEventArgs args = {System.Windows.Input.MouseButtonEventArgs}, bool reRaised = false)
PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender = {System.Windows.Shapes.Rectangle}, System.Windows.RoutedEventArgs args = {System.Windows.Input.MouseButtonEventArgs})
PresentationCore.dll!System.Windows.UIElement.RaiseTrustedEvent(System.Windows.RoutedEventArgs args = {System.Windows.Input.MouseButtonEventArgs})
PresentationCore.dll!System.Windows.UIElement.RaiseEvent(System.Windows.RoutedEventArgs args, bool trusted)
PresentationCore.dll!System.Windows.Input.InputManager.ProcessStagingArea()
PresentationCore.dll!System.Windows.Input.InputManager.ProcessInput(System.Windows.Input.InputEventArgs input)
PresentationCore.dll!System.Windows.Input.InputProviderSite.ReportInput(System.Windows.Input.InputReport inputReport)
PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.ReportInput(System.IntPtr hwnd, System.Windows.Input.InputMode mode, int timestamp, System.Windows.Input.RawMouseActions actions, int x, int y, int wheel)
PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.FilterMessage(System.IntPtr hwnd = 0x000406ce, MS.Internal.Interop.WindowMessage msg = WM_LBUTTONUP, System.IntPtr wParam = 0x00000000, System.IntPtr lParam = 0x005b0066, ref bool handled = false)
PresentationCore.dll!System.Windows.Interop.HwndSource.InputFilterMessage(System.IntPtr hwnd = 0x000406ce, int msg = 0x00000202, System.IntPtr wParam = 0x00000000, System.IntPtr lParam = 0x005b0066, ref bool handled = false)
WindowsBase.dll!MS.Win32.HwndWrapper.WndProc(System.IntPtr hwnd = 0x000406ce, int msg = 0x00000202, System.IntPtr wParam = 0x00000000, System.IntPtr lParam = 0x005b0066, ref bool handled = false)
WindowsBase.dll!MS.Win32.HwndSubclass.DispatcherCallbackOperation(object o)
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs)
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(object source = {System.Windows.Threading.Dispatcher}, System.Delegate callback, object args, int numArgs, System.Delegate catchHandler = null)
WindowsBase.dll!System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority priority, System.TimeSpan timeout, System.Delegate method, object args, int numArgs)
WindowsBase.dll!MS.Win32.HwndSubclass.SubclassWndProc(System.IntPtr hwnd = 0x000406ce, int msg = 0x00000202, System.IntPtr wParam = 0x00000000, System.IntPtr lParam = 0x005b0066)
[Native to Managed Transition]
[email protected]()
user32.dll!InternalCallWinProc()
user32.dll!UserCallWinProcCheckWow(struct _ACTIVATION_CONTEXT *,void *,struct HWND__ *,enum _WM_VALUE,unsigned int,long,void *,int)
[email protected]()
[email protected]()
WindowsBase.ni.dll!69d4936c()
[Frames below may be incorrect and/or missing, native debugger attempting to walk managed call stack]
[Managed to Native Transition]
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame = {System.Windows.Threading.DispatcherFrame})
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame)
PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore)
PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window)
PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window)
PresentationFramework.dll!System.Windows.Application.Run()
WpfApp1.exe!WpfApp1.App.Main()
[Native to Managed Transition]
[email protected]()
[email protected]()
[email protected]()
ntdll.dll!__RtlUserThreadStart()
[email protected]()

Просто для удовольствия здесь есть та же самая стекловидная графика, что и выше, в графической форме: Stacktrace

Итак, мое заключение состоит в том, что...

Ответ 5

Возможной работой может стать Try, Catch, наконец, исключение UIAnimation и не создавать никаких событий (ящиков сообщений, журналов ошибок), когда это происходит. Просто дайте коду продолжить, как будто ничего не произошло.