Пример #1
0
        /// <summary>
        /// This method tries to find the assembly of resources and the strongly
        /// typed Resource class in a project so the designer works properly.
        ///
        /// It's recommended your application ALWAYS explicitly initializes the
        /// DefaultResourceAssembly and DefaultResourceManager in LocalizationSettings.
        ///
        /// When running in the designer this code tries to find
        /// </summary>
        /// <returns></returns>
        internal bool FindDefaultResourceAssembly()
        {
            Assembly asm = null;

            if (this.Assembly != null)
            {
                asm = LocalizationSettings.AssemblyList[this.Assembly] as Assembly;
                if (asm == null)
                {
                    asm = LocalizationSettings.AddAssembly(this.Assembly);
                }
                return(true);
            }


            try
            {
                if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
                {
                    // in designer find the Windows.Application instance
                    // NOTE: will not work in control projects but better than nothing
                    asm = (
                        from a in AppDomain.CurrentDomain.GetAssemblies()
                        where a.EntryPoint != null &&
                        a.GetTypes().Any(t => t.IsSubclassOf(typeof(System.Windows.Application)))
                        select a
                        ).FirstOrDefault();
                }
                else
                {
                    // Do Private reflection on FrameworkElement
                    FrameworkElement element = _targetObject as FrameworkElement;
                    if (element != null)
                    {
                        object root = element.GetType().GetProperty("InheritanceParent", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(element, null);
                        asm = root.GetType().Assembly;
                    }
                }
            }
            catch
            { /* eat any exceptions here; */ }

            // Assume the Document we're called is in the same assembly as resources
            if (asm == null)
            {
                asm = System.Reflection.Assembly.GetExecutingAssembly();
            }

            // Search for Properties.Resources in the Exported Types (has to be public!)
            Type ResType = asm.GetExportedTypes().Where(type => type.FullName.Contains(".Properties.Resources")).FirstOrDefault();

            if (ResType == null)
            {
                return(false);
            }

            ResourceManager resMan = ResType.GetProperty("ResourceManager").GetValue(ResType, null) as ResourceManager;

            LocalizationSettings.Current.DefaultResourceAssembly = asm;
            LocalizationSettings.Current.DefaultResourceManager  = resMan;

            return(true);
        }