|
| 1 | +// This Source Code Form is subject to the terms of the MIT License. |
| 2 | +// If a copy of the MIT was not distributed with this file, You can obtain one at https://opensource.org/licenses/MIT. |
| 3 | +// Copyright (C) Leszek Pomianowski and WPF UI Contributors. |
| 4 | +// All Rights Reserved. |
| 5 | + |
| 6 | +using System; |
| 7 | +using System.Reflection; |
| 8 | +using System.Windows; |
| 9 | +using System.Windows.Threading; |
| 10 | + |
| 11 | +namespace PresentationFramework.Win11.Styles |
| 12 | +{ |
| 13 | + /// <summary> |
| 14 | + /// Overwrites ContextMenu-Style for some UIElements (like RichTextBox) that don't take the default ContextMenu-Style by default. |
| 15 | + /// <para>The code inside this CodeBehind-Class forces this ContextMenu-Style on these UIElements through Reflection (because it is only accessible through Reflection it is also only possible through CodeBehind and not XAML)</para> |
| 16 | + /// </summary> |
| 17 | + // This Code is based on a StackOverflow-Answer: https://stackoverflow.com/a/56736232/9759874 |
| 18 | + partial class ContextMenu : ResourceDictionary |
| 19 | + { |
| 20 | + /// <summary> |
| 21 | + /// Registers editing <see cref="ContextMenu"/> styles with <see cref="Dispatcher"/>. |
| 22 | + /// </summary> |
| 23 | + public ContextMenu() |
| 24 | + { |
| 25 | + // Run OnResourceDictionaryLoaded asynchronously to ensure other ResourceDictionary are already loaded before adding new entries |
| 26 | + Dispatcher |
| 27 | + .CurrentDispatcher |
| 28 | + .BeginInvoke(DispatcherPriority.Normal, new Action(OnResourceDictionaryLoaded)); |
| 29 | + } |
| 30 | + |
| 31 | + private void OnResourceDictionaryLoaded() |
| 32 | + { |
| 33 | + var currentAssembly = typeof(Application).Assembly; |
| 34 | + |
| 35 | + AddEditorContextMenuDefaultStyle(currentAssembly); |
| 36 | + } |
| 37 | + |
| 38 | + private void AddEditorContextMenuDefaultStyle(Assembly currentAssembly) |
| 39 | + { |
| 40 | + var contextMenuStyle = this["UiContextMenu"] as Style; |
| 41 | + var editorContextMenuType = Type.GetType( |
| 42 | + "System.Windows.Documents.TextEditorContextMenu+EditorContextMenu, " + currentAssembly |
| 43 | + ); |
| 44 | + |
| 45 | + if (editorContextMenuType == null || contextMenuStyle == null) |
| 46 | + return; |
| 47 | + |
| 48 | + var editorContextMenuStyle = new Style(editorContextMenuType, contextMenuStyle); |
| 49 | + Add(editorContextMenuType, editorContextMenuStyle); |
| 50 | + } |
| 51 | + } |
| 52 | +} |
0 commit comments