/* This Code is based on a StackOverflow-Answer: https://stackoverflow.com/a/56736232/9759874 */ using System.Reflection; using System.Windows.Threading; namespace WPFluent.Controls; /// /// Overwrites ContextMenu-Style for some UIElements (like RichTextBox) that don't take the default ContextMenu-Style by /// default. 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) /// public partial class ContextMenuLoader : ResourceDictionary { /// /// Initializes a new instance of the class and registers editing styles defined in /// "ContextMenu.xaml" with the . /// public ContextMenuLoader() { // Run OnResourceDictionaryLoaded asynchronously to ensure other ResourceDictionary are already loaded before adding new entries Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(OnResourceDictionaryLoaded)); } private void AddEditorContextMenuDefaultStyle(Assembly currentAssembly) { var editorContextMenuType = Type.GetType( $"System.Windows.Documents.TextEditorContextMenu+EditorContextMenu, {currentAssembly}"); ResourceDictionary resourceDict = new() { Source = new Uri("pack://application:,,,/WPFluent;component/Controls/ContextMenu/ContextMenu.xaml"), }; Style contextMenuStyle = (Style)resourceDict["UiContextMenu"]; if (editorContextMenuType is null || contextMenuStyle is null) { return; } var editorContextMenuStyle = new Style(editorContextMenuType, contextMenuStyle); Add(editorContextMenuType, editorContextMenuStyle); } private void OnResourceDictionaryLoaded() { Assembly currentAssembly = typeof(Application).Assembly; AddEditorContextMenuDefaultStyle(currentAssembly); } }