Example #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);
        }
Example #2
0
        static void TranslateKeys(UIElement element)
        {
            if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(element))
            {
                return;
            }

            FrameworkElement root = WpfUtils.GetRootVisual(element) as FrameworkElement;

            if (root == null)
            {
                return; // must be framework element to find root
            }
            // Retrieve the resource set and assembly from the top level element
            string resourceset      = root.GetValue(TranslateResourceSetProperty) as string;
            string resourceAssembly = root.GetValue(TranslateResourceAssemblyProperty) as string;

            if (element is FrameworkElement && ((FrameworkElement)element).Name == "lblLocale")
            {
                root = root;
            }


            ResourceManager manager = null;

            if (resourceAssembly == null)
            {
                manager = LocalizationSettings.GetResourceManager(resourceset, root.GetType().Assembly);
            }
            else
            {
                manager = LocalizationSettings.GetResourceManager(resourceset, resourceAssembly);
            }

            // find neutral culture so we can iterate over all keys


            ResourceSet           set        = manager.GetResourceSet(CultureInfo.InvariantCulture, true, true);
            IDictionaryEnumerator enumerator = set.GetEnumerator();

            while (enumerator.MoveNext())
            {
                string key = enumerator.Key as string;
                if (key.StartsWith(element.Uid + "."))
                {
                    string property = key.Split('.')[1] as string;
                    object value    = manager.GetObject(key); // enumerator.Value;

                    // Bind the value AFTER control has initialized or else the
                    // default will override what we bind here
                    root.Initialized += delegate
                    {
                        try
                        {
                            PropertyInfo prop = element.GetType().GetProperty(property, BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.IgnoreCase);
                            prop.SetValue(element, value, null);
                        }
                        catch (Exception ex)
                        {
                            Trace.WriteLine(string.Format("TranslateExtension Resource Failure: {0}  - {1}", key, ex.Message));
                        }
                    };
                }
            }
        }
Example #3
0
        /// <summary>
        /// Internal value retrieval
        /// </summary>
        /// <returns></returns>
        private object ProvideValueInternal()
        {
            object localized = null;

            if (Static == null)
            {
                // Get a cached resource manager for this resource set
                ResourceManager resMan = LocalizationSettings.GetResourceManager(this.ResourceSet, this.Assembly);

                // Get the localized value
                if (resMan != null)
                {
                    try
                    {
                        localized = resMan.GetObject(this.Id);
                    }
                    catch { /* eat exception here so we can still display default value */ }
                }
            }
            else
            {
                try
                {
                    // Parse Static=properties:Resources.HelloWorld like static resource
                    int index = this.Static.IndexOf('.');
                    if (index == -1)
                    {
                        throw new ArgumentException(Resources.InvalidStaticBindingSyntax + ": "
                                                    + this.Static);
                    }

                    if (this._propertyInfo == null)
                    {
                        // resolve properties:Resources
                        string            typeName = this.Static.Substring(0, index);
                        IXamlTypeResolver service  = _serviceProvider.GetService(typeof(IXamlTypeResolver))
                                                     as IXamlTypeResolver;
                        Type memberType = service.Resolve(typeName);

                        string propName = this.Static.Substring(index + 1);
                        this._propertyInfo = memberType.GetProperty(propName,
                                                                    BindingFlags.Public | BindingFlags.Static |
                                                                    BindingFlags.FlattenHierarchy);
                    }
                    localized = _propertyInfo.GetValue(null, null);
                }
                catch
                {
                    // in Blend this will always fail and fall through to use the Default
                    // values

                    // Since this is a static property lets throw here
                    //This way you'll see it - in the designer as an error.
                    //throw new ArgumentException(Resources.InvalidStaticBindingSyntax + ": " +
                    //                            this.Static + "\r\n" + ex.Message);
                }
            }

            // If the value is null, use the Default value if available
            if (localized == null && this.Default != null)
            {
                localized = this.Default;
            }

            // fail type conversions silently and write to trace output
            try
            {
                // Convert if a type converter is availalbe
                if (localized != null &&
                    this.Converter == null &&
                    _typeConverter != null &&
                    _typeConverter.CanConvertFrom(localized.GetType()))
                {
                    localized = _typeConverter.ConvertFrom(localized);
                }

                // Apply a type converter if one was specified
                if (Converter != null)
                {
                    localized = this.Converter.Convert(localized, _targetProperty.PropertyType,
                                                       null, CultureInfo.CurrentCulture);
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format(Resources.ConversionErrorMessageFormatString,
                                              Id, ex.Message));
                //Trace.WriteLine(string.Format("ResExtension Type conversion failed. Id: {0},
                // Error: {1}", Id, ex.Message));

                localized = null;
            }

            // If no fallback value is available, return the key
            if (localized == null)
            {
                if (_targetProperty != null &&
                    _targetProperty.PropertyType == typeof(string))
                {
                    // Return the key surrounded by question marks for string type properties
                    localized = string.Concat("?", Id, "?");
                }
                else
                {
                    // Return the UnsetValue for all other types of dependency properties
                    return(DependencyProperty.UnsetValue);
                }
            }

            // Format if a format string was provided
            if (this.Format != null)
            {
                localized = string.Format(CultureInfo.CurrentUICulture,
                                          this.Format, localized);
            }

            return(localized);
        }