/// <summary> /// Determines the <see cref="ResourceManager"/> to use for the specified <see cref="DependencyObject"/>. /// </summary> /// <param name="obj"></param> /// <returns></returns> /// <exception cref="InvalidOperationException">The method is not called on the UI thread of the specified <see cref="DependencyObject"/>.</exception> public static ResourceManager GetResourceManager(DependencyObject obj) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } obj.VerifyAccess(); var resourceManager = LocalizationScope.GetResourceManager(obj); if (resourceManager == null) { if (DesignerProperties.GetIsInDesignMode(obj)) { // Window.GetWindow returns "null" at design time return(GetDefaultResourceManagerForAssembly(DesignTimeHelper.GetDesignTimeAssembly())); } else { var window = Window.GetWindow(obj); if (window != null) { var localValue = window.ReadLocalValue(DefaultResourceManagerProperty); if (localValue == DependencyProperty.UnsetValue) { resourceManager = GetDefaultResourceManagerForAssembly(window.GetType().Assembly); window.SetValue(DefaultResourceManagerProperty, resourceManager); } else { resourceManager = localValue as ResourceManager; } } } } return(resourceManager); }
public override object ProvideValue(IServiceProvider serviceProvider) { if (serviceProvider == null) { throw new ArgumentNullException(nameof(serviceProvider)); } if (!(serviceProvider.GetService(typeof(IProvideValueTarget)) is IProvideValueTarget service)) { return(null); } Assembly assembly; if (service.TargetObject is DependencyObject depObj && DesignerProperties.GetIsInDesignMode(depObj)) { // WPF Designer uses an instance of "System.Windows.Controls.UserControl" to represent a user control // (not the actual type) and "Microsoft.VisualStudio.DesignTools.WpfDesigner.InstanceBuilders.WindowInstance" // to represent a mock window if (depObj is UserControl || (depObj is FrameworkElement frameworkElement && frameworkElement.Parent == null)) { // The element is a user control or a root element (e.g. a mock-up window - WindowInstance) // Check if the object is a mock object or an actual instance. If it is an actual instance then // the user control is used in another user control or a window if (depObj.GetType() == typeof(UserControl) || DesignTimeHelper.IsWpfDesignerAssembly(depObj.GetType().Assembly)) { // The object is a mock object; therefore, use the design-time assembly assembly = DesignTimeHelper.GetDesignTimeAssembly(); } else { // The object is an actual instance assembly = depObj.GetType().Assembly; } }