static object RecurseDictionaries(ResourceDictionary dictionary, string name)
		{
			if (dictionary.Contains(name)) return dictionary[name];

			return dictionary.MergedDictionaries
				.Select(child => RecurseDictionaries(child, name))
				.FirstOrDefault(candidate => candidate != null);
		}
        private static void AdjustResourceColor(ResourceDictionary resources, string sourceKey, string targetKey, float factor)
        {
            if (!resources.Contains(sourceKey))
                return;

            var sourceColor = (Color)resources[sourceKey];
            var targetColor = sourceColor.ToBrightened(factor);

            if (resources.Contains(targetKey))
            {
                resources[targetKey] = targetColor;
            }
            else
            {
                resources.Add(targetKey, targetColor);
            }
        }
Example #3
0
 private void ChangeRd(ResourceDictionary rd, string newKey, object newValue)
 {
     if (!rd.Contains(newKey))
     {
         rd.Add(newKey, newValue);
         SaveChange();
     }
 }
        private static DataTemplate TryFindDataTemplate(ResourceDictionary resourceDictionary, string contentTypeName)
        {
            DataTemplate dataTemplate = null;
            if (resourceDictionary.Contains(contentTypeName))
            {
                dataTemplate = resourceDictionary[contentTypeName] as DataTemplate;
            }

            return dataTemplate;
        }
 private static bool TryGetValue(ResourceDictionary dict, string key, out object val)
 {
     val = null;
     if (!dict.Contains(key))
     {
         return false;
     }
     val = dict[key];
     return true;
 }
Example #6
0
        private static void ApplyResourceDictionary(ResourceDictionary newRd, ResourceDictionary oldRd)
        {
            foreach (DictionaryEntry r in newRd)
            {
                if (oldRd.Contains(r.Key))
                    oldRd.Remove(r.Key);

                oldRd.Add(r.Key, r.Value);
            }
        }
Example #7
0
 private object GetValueFromDictionary(string key, ResourceDictionary dictionary)
 {
     if (dictionary.Contains(key))
     {
         return dictionary[key];
     }
     foreach (var resourceDictionary in dictionary.MergedDictionaries)
     {
         var result = GetValueFromDictionary(key, resourceDictionary);
         if (result != null) return result;
     }
     return null;
 }
        public BitmapSource GetIcon(string pResourceName, string pModule)
        {
            var resourceDictionaryUri = new Uri(
                string.Format("/{0};component/{1}/Images.xaml", GetType().Assembly.GetName().Name, pModule),
                UriKind.RelativeOrAbsolute);

            var resourceDictionary = new ResourceDictionary { Source = resourceDictionaryUri };
            if (!resourceDictionary.Contains(pResourceName))
            {
                throw new ArgumentException(string.Format("the resource {0} could not be found on resource dictionary {1}", pResourceName, resourceDictionaryUri));
            }

            var resource = resourceDictionary[pResourceName];
            return resource as BitmapSource;
        }
Example #9
0
        public object this[object key] {
            get {
                if (!(key is string || key is Type))
                {
                    throw new ArgumentException("Key must be a string or Type");
                }

                // check our cache
                if (managedDict != null && managedDict.ContainsKey(key))
                {
                    return(managedDict[key]);
                }

                // now iterate over the merged dictionaries
                PresentationFrameworkCollection <ResourceDictionary> col = MergedDictionaries;
                for (int i = col.Count - 1; i >= 0; i--)
                {
                    ResourceDictionary rd = col[i];

                    if (rd.Contains(key))
                    {
                        return(rd[key]);
                    }
                }

                return(null);
            }
            set {
                // this setter only permits string
                // keys.  since unmanaged needs to
                // access them we send it along to
                // unmanaged as well as update our
                // cache.
                var str_key = ToStringKey(key);

                using (var val = Value.FromObject(value, true)) {
                    var v = val;
                    if (NativeMethods.resource_dictionary_set(native, str_key, ref v))
                    {
                        if (managedDict == null)
                        {
                            managedDict = new Dictionary <object, object> ();
                        }
                        managedDict.Add(str_key, value);
                    }
                }
            }
        }
        private static void ChangeTheme(ResourceDictionary resources, Tuple<Theme, Accent> oldThemeInfo, Accent accent, Theme newTheme)
        {
            if (oldThemeInfo != null)
            {
                var oldAccent = oldThemeInfo.Item2;
                if (oldAccent != null && oldAccent.Name != accent.Name)
                {
                    var accentResource = resources.MergedDictionaries.FirstOrDefault(d => d.Source == oldAccent.Resources.Source);
                    if (accentResource != null) {
                        var ok = resources.MergedDictionaries.Remove(accentResource);
                        // really need this???
                        foreach (DictionaryEntry r in accentResource)
                        {
                            if (resources.Contains(r.Key))
                                resources.Remove(r.Key);
                        }

                        resources.MergedDictionaries.Add(accent.Resources);
                    }
                }

                var oldTheme = oldThemeInfo.Item1;
                if (oldTheme != null && oldTheme != newTheme)
                {
                    var oldThemeResource = (oldTheme == Theme.Light) ? LightResource : DarkResource;
                    var md = resources.MergedDictionaries.FirstOrDefault(d => d.Source == oldThemeResource.Source);
                    if (md != null)
                    {
                        var ok = resources.MergedDictionaries.Remove(md);
                        var newThemeResource = (newTheme == Theme.Light) ? LightResource : DarkResource;
                        // really need this???
                        foreach (DictionaryEntry r in oldThemeResource)
                        {
                            if (resources.Contains(r.Key))
                                resources.Remove(r.Key);
                        }

                        resources.MergedDictionaries.Add(newThemeResource);
                    }
                }
            }
            else
            {
                ChangeTheme(resources, accent, newTheme);
            }
        }
Example #11
0
      static Transitions() {
         var dict = new ResourceDictionary {
            Source = typeof(Transitions).Assembly.ToPackUri("Mpcr.Core.Wpf.Transitions/Primitives/TransitionStoryboards.xaml") 
         };

         foreach (var prop in typeof(Transitions).GetStaticProperties(true, true)) {
            var propKey = "@{0}".Substitute(prop.Name);
            Assumption.IsTrue(dict.Contains(propKey), "Standard transition '{0}' is not defined", prop.Name);
            var transition = dict[propKey] as Transition;
            Assumption.IsA(transition, prop.PropertyType, "Standard transition '{0}' is not of the expected type '{1}'", prop.Name, prop.PropertyType);
            if (transition is StoryboardTransition2D) {
               var stb = (StoryboardTransition2D)transition;
               if (stb.NewContentStyle != null) stb.NewContentStyle.Seal();
               if (stb.OldContentStyle != null) stb.OldContentStyle.Seal();
            }
            transition.Freeze();
            prop.SetValue(null, transition, null);
         }
      }
 public static void BeginElementStoryboard(ResourceDictionary resources, UIElement target, string subTargetName, string StoryboardName, PropertyPath propertyPath, EventHandler completedHandler)
 {
     if (!resources.Contains(StoryboardName))
     {
         throw new ArgumentException(string.Format("Resource with name {0} not found!", StoryboardName));
     }
     if (!string.IsNullOrEmpty(subTargetName))
     {
         target = (target as FrameworkElement).FindName(subTargetName) as UIElement;
     }
     Storyboard sbAlpha = resources[StoryboardName] as Storyboard;
     Storyboard sb = CloneStoryboard(sbAlpha);
     Storyboard.SetTarget(sb, target);
     Storyboard.SetTargetProperty(sb, propertyPath);
     if (completedHandler != null)
     {
         sb.Completed += completedHandler;
     }
     sb.Begin();
 }
        // Token: 0x06000865 RID: 2149 RVA: 0x0001B4E8 File Offset: 0x000196E8
        private ResourceDictionary FindTheResourceDictionary(IServiceProvider serviceProvider, bool isDeferredContentSearch)
        {
            IXamlSchemaContextProvider xamlSchemaContextProvider = serviceProvider.GetService(typeof(IXamlSchemaContextProvider)) as IXamlSchemaContextProvider;

            if (xamlSchemaContextProvider == null)
            {
                throw new InvalidOperationException(SR.Get("MarkupExtensionNoContext", new object[]
                {
                    base.GetType().Name,
                    "IXamlSchemaContextProvider"
                }));
            }
            IAmbientProvider ambientProvider = serviceProvider.GetService(typeof(IAmbientProvider)) as IAmbientProvider;

            if (ambientProvider == null)
            {
                throw new InvalidOperationException(SR.Get("MarkupExtensionNoContext", new object[]
                {
                    base.GetType().Name,
                    "IAmbientProvider"
                }));
            }
            XamlSchemaContext schemaContext = xamlSchemaContextProvider.SchemaContext;
            XamlType          xamlType      = schemaContext.GetXamlType(typeof(FrameworkElement));
            XamlType          xamlType2     = schemaContext.GetXamlType(typeof(Style));
            XamlType          xamlType3     = schemaContext.GetXamlType(typeof(FrameworkTemplate));
            XamlType          xamlType4     = schemaContext.GetXamlType(typeof(Application));
            XamlType          xamlType5     = schemaContext.GetXamlType(typeof(FrameworkContentElement));
            XamlMember        member        = xamlType5.GetMember("Resources");
            XamlMember        member2       = xamlType.GetMember("Resources");
            XamlMember        member3       = xamlType2.GetMember("Resources");
            XamlMember        member4       = xamlType2.GetMember("BasedOn");
            XamlMember        member5       = xamlType3.GetMember("Resources");
            XamlMember        member6       = xamlType4.GetMember("Resources");

            XamlType[] types = new XamlType[]
            {
                schemaContext.GetXamlType(typeof(ResourceDictionary))
            };
            IEnumerable <AmbientPropertyValue> allAmbientValues = ambientProvider.GetAllAmbientValues(null, isDeferredContentSearch, types, new XamlMember[]
            {
                member,
                member2,
                member3,
                member4,
                member5,
                member6
            });
            List <AmbientPropertyValue> list = allAmbientValues as List <AmbientPropertyValue>;

            for (int i = 0; i < list.Count; i++)
            {
                AmbientPropertyValue ambientPropertyValue = list[i];
                if (ambientPropertyValue.Value is ResourceDictionary)
                {
                    ResourceDictionary resourceDictionary = (ResourceDictionary)ambientPropertyValue.Value;
                    if (resourceDictionary.Contains(this.ResourceKey))
                    {
                        return(resourceDictionary);
                    }
                }
                if (ambientPropertyValue.Value is Style)
                {
                    Style style = (Style)ambientPropertyValue.Value;
                    ResourceDictionary resourceDictionary2 = style.FindResourceDictionary(this.ResourceKey);
                    if (resourceDictionary2 != null)
                    {
                        return(resourceDictionary2);
                    }
                }
            }
            return(null);
        }
Example #14
0
		public void InterfaceTest ()
		{
			IDictionary<object, object> d = new ResourceDictionary ();
			Assert.Throws<ArgumentException> (delegate {
				d.Add (new KeyValuePair<object, object> (new object (), new object ()));
			}, "#1");
			d.Add (new KeyValuePair<object, object> ("bob", new object ()));
			Assert.Throws<NotImplementedException> (delegate {
				int a = d.Count;
				GC.KeepAlive (a);
			}, "#2");
			Assert.AreEqual (1, ((ResourceDictionary) d).Count, "#3");
			Assert.Throws<ArgumentException> (delegate {
				d.Add (new object (), new object ());
			}, "#4");
			d.Add ("str", new object ());
			Assert.AreEqual (2, ((ResourceDictionary) d).Count, "#5");
			Assert.Throws<ArgumentException> (delegate {
				d.ContainsKey (new object ());
			}, "#6");
			Assert.IsTrue (d.Contains (new KeyValuePair<object, object> ("str", new object ())), "#7");
			d.Clear ();
			Assert.AreEqual (0, ((ResourceDictionary) d).Count, "#8");

			// this doesn't throw in SL4 for any runtime version
			d.GetEnumerator ();

			Assert.Throws<NotImplementedException> (delegate {
				var v = d.Keys;
				GC.KeepAlive (v);
			}, "#10");
			Assert.Throws<NotImplementedException> (delegate {
				var v = d.Values;
				GC.KeepAlive (v);
			}, "#11");
			Assert.IsFalse (d.IsReadOnly, "#12");
			Assert.Throws<NotImplementedException> (delegate {
				d.CopyTo (new KeyValuePair<object, object> [10], 0);
			}, "#13");
		}
Example #15
0
		public void Contains_TypeAndStringInResourceDictionary_TypeSecond()
		{
			var rd = new ResourceDictionary();
			rd.Add("System.Windows.Controls.Button", "System.Windows.Controls.Button");
			Assert.IsTrue(rd.Contains("System.Windows.Controls.Button"), "#1");
			Assert.IsFalse (rd.Contains(typeof (Button)), "#2");

			Assert.Throws<ArgumentException>(() => {
				rd.Add(typeof(Button), new Style { TargetType = typeof(Button) });
			}, "#3");
		}
Example #16
0
		public void Contains_TypeAndStringInResourceDictionary_TypeFirst()
		{
			var rd = new ResourceDictionary();
			rd.Add(typeof(Button), new Style { TargetType = typeof(Button) });
			rd.Add("System.Windows.Controls.Button", "System.Windows.Controls.Button");

			Assert.IsTrue(rd.Contains(typeof(Button)), "#1");
			Assert.IsTrue(rd.Contains("System.Windows.Controls.Button"), "#2");

			rd.Remove(typeof(Button));
			Assert.IsFalse(rd.Contains(typeof(Button)), "#3");
			Assert.IsTrue(rd.Contains("System.Windows.Controls.Button"), "#4");
		}
Example #17
0
		public void Contains_TypeNameAsKeyStyleWithTargetTypeSet_ReturnsFalse ()
		{
			ResourceDictionary rd = new ResourceDictionary ();

			Style s = new Style () {
				TargetType = typeof (Button),
			};

			rd.Add (typeof (Button), s);

			bool contains = rd.Contains ("System.Windows.Controls.Button");
			Assert.IsFalse (contains);
		}
Example #18
0
        /// <summary>
        /// Creates style forwarders for default styles. This means that all styles found in the theme that are
        /// name like Default[CONTROLNAME]Style (i.e. "DefaultButtonStyle") will be used as default style for the
        /// control.
        /// This method will use the passed resources.
        /// </summary>
        /// <param name="rootResourceDictionary">The root resource dictionary.</param>
        /// <param name="sourceResources">Resource dictionary to read the keys from (thus that contains the default styles).</param>
        /// <param name="targetResources">Resource dictionary where the forwarders will be written to.</param>
        /// <param name="forceForwarders">if set to <c>true</c>, styles will not be completed but only forwarders are created.</param>
        /// <param name="defaultPrefix">The default prefix, uses to determine the styles as base for other styles.</param>
        /// <param name="recreateStylesBasedOnTheme">if set to <c>true</c>, the styles will be recreated with BasedOn on the current theme.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="rootResourceDictionary" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="sourceResources" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="targetResources" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">The <paramref name="defaultPrefix" /> is <c>null</c> or whitespace.</exception>
        public static void CreateStyleForwardersForDefaultStyles(ResourceDictionary rootResourceDictionary, ResourceDictionary sourceResources,
            ResourceDictionary targetResources, bool forceForwarders, string defaultPrefix = DefaultKeyPrefix, bool recreateStylesBasedOnTheme = false)
        {
            Argument.IsNotNull("rootResourceDictionary", rootResourceDictionary);
            Argument.IsNotNull("sourceResources", sourceResources);
            Argument.IsNotNull("targetResources", targetResources);
            Argument.IsNotNullOrWhitespace("defaultPrefix", defaultPrefix);

            #region If forced, use old mechanism
            if (forceForwarders)
            {
                // Get all keys from this resource dictionary
                var keys = (from key in sourceResources.Keys as ICollection<object>
                            where key is string &&
                                  ((string)key).StartsWith(defaultPrefix, StringComparison.Ordinal) &&
                                  ((string)key).EndsWith(DefaultKeyPostfix, StringComparison.Ordinal)
                            select key).ToList();

                foreach (string key in keys)
                {
                    var style = sourceResources[key] as Style;
                    if (style != null)
                    {
                        Type targetType = style.TargetType;
                        if (targetType != null)
                        {
                            try
                            {
#if NET
                                var styleForwarder = new Style(targetType, style);
#else
                                var styleForwarder = new Style(targetType);
                                styleForwarder.BasedOn = style;
#endif
                                targetResources.Add(targetType, styleForwarder);
                            }
                            catch (Exception ex)
                            {
                                Log.Warning(ex, "Failed to create style forwarder for '{0}'", key);
                            }
                        }
                    }
                }

                foreach (var resourceDictionary in sourceResources.MergedDictionaries)
                {
                    CreateStyleForwardersForDefaultStyles(rootResourceDictionary, resourceDictionary, targetResources, forceForwarders, defaultPrefix);
                }

                return;
            }
            #endregion

            var defaultStyles = FindDefaultStyles(sourceResources, defaultPrefix);
            foreach (var defaultStyle in defaultStyles)
            {
                try
                {
                    var targetType = defaultStyle.TargetType;
                    if (targetType != null)
                    {
                        bool hasSetStyle = false;

                        var resourceDictionaryDefiningStyle = FindResourceDictionaryDeclaringType(targetResources, targetType);
                        if (resourceDictionaryDefiningStyle != null)
                        {
                            var style = resourceDictionaryDefiningStyle[targetType] as Style;
                            if (style != null)
                            {
                                Log.Debug("Completing the style info for '{0}' with the additional info from the default style definition", targetType);

                                resourceDictionaryDefiningStyle[targetType] = CompleteStyleWithAdditionalInfo(style, defaultStyle);
                                hasSetStyle = true;
                            }
                        }

                        if (!hasSetStyle)
                        {
                            Log.Debug("Couldn't find style definition for '{0}', creating style forwarder", targetType);

#if NET
                            var style = new Style(targetType, defaultStyle);
                            if (!targetResources.Contains(targetType))
                            {
                                targetResources.Add(targetType, style);
                            }
#else
                            var targetStyle = new Style(targetType);
                            targetStyle.BasedOn = defaultStyle;
                            targetResources.Add(targetType, targetStyle);
#endif
                        }
                    }
                }
                catch (Exception)
                {
                    Log.Warning("Failed to complete the style for '{0}'", defaultStyle);
                }
            }

#if NET
            if (recreateStylesBasedOnTheme)
            {
                RecreateDefaultStylesBasedOnTheme(rootResourceDictionary, targetResources, defaultPrefix);
            }
#endif

            IsStyleForwardingEnabled = true;
        }
Example #19
0
        /// <summary>
        /// Loads the standard activity icons from System.Activities.Presentation.
        /// Accepts various forms of input including 'short name' i.e. toolbox display name, and 'Type.FullName' - and tries to fix them automatically.
        /// </summary>
        private static object ExtractIconResource(string iconOrtypeName)
        {
            iconsDict = iconsDict ?? new ResourceDictionary
            {
                Source = new Uri("pack://application:,,,/System.Activities.Presentation;component/themes/icons.xaml")
            };

            string resourceKey = GetResourceName(iconOrtypeName);
            object resource = iconsDict.Contains(resourceKey) ? iconsDict[resourceKey] : null;

            if (!(resource is DrawingBrush))
            {
                resource = iconsDict["GenericLeafActivityIcon"];
            }

            return resource;
        }
        /// <summary>
        /// Replaces a certain entry anywhere in the parent dictionary and its merged dictionaries
        /// </summary>
        /// <param name="entryName">The entry to replace</param>
        /// <param name="newValue">The new entry value</param>
        /// <param name="parentDictionary">The root dictionary to start searching at. Null means using Application.Current.Resources</param>
        private static void ReplaceEntry(object entryName, object newValue, ResourceDictionary parentDictionary = null)
        {
            if (parentDictionary == null)
                parentDictionary = Application.Current.Resources;

            if (parentDictionary.Contains(entryName))
            {
                var brush = parentDictionary[entryName] as SolidColorBrush;
                if (brush != null && !brush.IsFrozen)
                {
                    var animation = new ColorAnimation
                    {
                        From = ((SolidColorBrush)parentDictionary[entryName]).Color,
                        To = ((SolidColorBrush)newValue).Color,
                        Duration = new Duration(TimeSpan.FromMilliseconds(300))
                    };
                    brush.BeginAnimation(SolidColorBrush.ColorProperty, animation);
                }
                else
                    parentDictionary[entryName] = newValue; //Set value normally
            }

            foreach (var dictionary in parentDictionary.MergedDictionaries)
                ReplaceEntry(entryName, newValue, dictionary);
        }
 private static bool SetItem(ResourceDictionary dictionary, object key, object item)
 {
     if (dictionary.Contains(key))
         return false;
     dictionary.Add(key, item);
     return true;
 }
Example #22
0
        /// <summary>
        /// Создаёт объект языка на основе словаря ресурсов
        /// </summary>
        /// <param name="rdOneLanguage">Словарь ресурсов на основании которого будет создан новый объект языка</param>
        /// <returns></returns>
        public OneLanguage CreateOneLanguage(ResourceDictionary rdOneLanguage)
        {
            OneLanguage lang = new OneLanguage();
            lang.ResourceDictionary = rdOneLanguage;

            if (rdOneLanguage.Contains("LanguageDisplayName"))
            {
                lang.Name = (string)rdOneLanguage["LanguageDisplayName"];
            }

            if (rdOneLanguage.Contains("LanguageCulture"))
            {
                string cult = (string)rdOneLanguage["LanguageCulture"];
                foreach (var c in CultureInfo.GetCultures(CultureTypes.AllCultures))
                {
                    if (c.Name == cult)
                    {
                       lang.Culture = new CultureInfo(c.Name);
                    }
                }
            }

            return lang;
        }
        /// <summary>
        /// Replaces a certain entry anywhere in the parent dictionary and its merged dictionaries
        /// </summary>
        /// <param name="entryName">The entry to replace</param>
        /// <param name="newValue">The new entry value</param>
        /// <param name="parentDictionary">The root dictionary to start searching at. Null means using Application.Current.Resources</param>
        /// <returns>Weather the value was replaced (true) or not (false)</returns>
        private static bool ReplaceEntry(object entryName, object newValue, ResourceDictionary parentDictionary = null)
        {
            if (parentDictionary == null)
                parentDictionary = Application.Current.Resources;

            if (parentDictionary.Contains(entryName))
            {
                parentDictionary[entryName] = newValue;
                return true;
            }

            foreach (var dictionary in parentDictionary.MergedDictionaries)
            {
                if (ReplaceEntry(entryName, newValue, dictionary))
                    return true;
            }

            return false;
        }
Example #24
0
		public void Contains_TypeAsKeyStyleWithTargetTypeSet_ReturnsTrue ()
		{
			ResourceDictionary rd = new ResourceDictionary ();

			Style s = new Style () {
				TargetType = typeof (Button),
			};

			rd.Add (typeof (Button), s);

			bool contains = rd.Contains (typeof (Button));
			Assert.IsTrue (contains);
		}
Example #25
0
		public void MergedDictionary_Contains ()
		{
			// 'Contains' looks up the merged dictionaries too
			var d1 = new ResourceDictionary ();
			var d2 = new ResourceDictionary ();
			d2.Add ("string", "string2");
			d1.MergedDictionaries.Add (d2);
			Assert.IsTrue(d1.Contains ("string"), "#1");
		}
Example #26
0
        /// <summary>
        /// Gets a <see cref="FrameworkTemplate"/> based on the specified parameters.
        /// </summary>
        /// <param name="xmlElement">The xml element to get template xaml from.</param>
        /// <param name="parentObject">The <see cref="XamlObject"/> to use as source for resources and contextual information.</param>
        /// <returns>A <see cref="FrameworkTemplate"/> based on the specified parameters.</returns>
        public static FrameworkTemplate GetFrameworkTemplate(XmlElement xmlElement, XamlObject parentObject)
        {
            var nav = xmlElement.CreateNavigator();

            var ns = new Dictionary<string, string>();
            while (true)
            {
                var nsInScope = nav.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml);
                foreach (var ak in nsInScope)
                {
                    if (!ns.ContainsKey(ak.Key) && ak.Key != "")
                        ns.Add(ak.Key, ak.Value);
                }
                if (!nav.MoveToParent())
                    break;
            }

            xmlElement = (XmlElement)xmlElement.CloneNode(true);

            foreach (var dictentry in ns.ToList())
            {
                var value = dictentry.Value;
                if (value.StartsWith("clr-namespace") && !value.Contains(";assembly=")) {
                    if (!string.IsNullOrEmpty(parentObject.OwnerDocument.CurrentProjectAssemblyName)) {
                        value += ";assembly=" + parentObject.OwnerDocument.CurrentProjectAssemblyName;
                    }
                }
                xmlElement.SetAttribute("xmlns:" + dictentry.Key, value);
            }

            var keyAttrib = xmlElement.GetAttribute("Key", XamlConstants.XamlNamespace);

            if (string.IsNullOrEmpty(keyAttrib)) {
                xmlElement.SetAttribute("Key", XamlConstants.XamlNamespace, "$$temp&&§§%%__");
            }

            var xaml = xmlElement.OuterXml;
            xaml = "<ResourceDictionary xmlns=\"http://schemas.microsoft.com/netfx/2007/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">" + xaml + "</ResourceDictionary>";
            StringReader stringReader = new StringReader(xaml);
            XmlReader xmlReader = XmlReader.Create(stringReader);
            var xamlReader = new XamlXmlReader(xmlReader, parentObject.ServiceProvider.SchemaContext);

            var seti = new XamlObjectWriterSettings();

            var resourceDictionary = new ResourceDictionary();
            var obj = parentObject;
            while (obj != null)
            {
                if (obj.Instance is ResourceDictionary)
                {
                    var r = obj.Instance as ResourceDictionary;
                    foreach (var k in r.Keys)
                    {
                        if (!resourceDictionary.Contains(k))
                            resourceDictionary.Add(k, r[k]);
                    }
                }
                else if (obj.Instance is FrameworkElement)
                {
                    var r = ((FrameworkElement)obj.Instance).Resources;
                    foreach (var k in r.Keys)
                    {
                        if (!resourceDictionary.Contains(k))
                            resourceDictionary.Add(k, r[k]);
                    }
                }

                obj = obj.ParentObject;
            }

            seti.BeforePropertiesHandler = (s, e) =>
            {
                if (seti.BeforePropertiesHandler != null)
                {
                    var rr = e.Instance as ResourceDictionary;
                    rr.MergedDictionaries.Add(resourceDictionary);
                    seti.BeforePropertiesHandler = null;
                }
            };

            var writer = new XamlObjectWriter(parentObject.ServiceProvider.SchemaContext, seti);

            XamlServices.Transform(xamlReader, writer);

            var result = (ResourceDictionary)writer.Result;

            var enr = result.Keys.GetEnumerator();
            enr.MoveNext();
            var rdKey = enr.Current;

            var template = result[rdKey] as FrameworkTemplate;

            result.Remove(rdKey);
            return template;
        }
Example #27
0
        void UpdateSupports( ResourceDictionary skin )
        {
            if (skin.Contains("Supports"))
                CurrentSupports = (string)skin["Supports"];
            else
                CurrentSupports = "";

            // CheckSupports
            if (options != null)
                options.Supports = CurrentSupports;
        }
Example #28
0
		public void Contains_TypeAsKey_DoesNotThrow ()
		{
			ResourceDictionary rd = new ResourceDictionary ();

			rd.Contains (typeof (TextBlock));
		}
Example #29
0
        private static Brush GetBrush(ResourceDictionary properties)
        {
            if (properties == null)
                return Brushes.Transparent;

            if (properties.Contains(EditorFormatDefinition.BackgroundColorId))
            {
                var color = (Color)properties[EditorFormatDefinition.BackgroundColorId];
                var brush = new SolidColorBrush(color);
                if (brush.CanFreeze)
                {
                    brush.Freeze();
                }
                return brush;
            }
            if (properties.Contains(EditorFormatDefinition.BackgroundBrushId))
            {
                var brush = (Brush)properties[EditorFormatDefinition.BackgroundBrushId];
                if (brush.CanFreeze)
                {
                    brush.Freeze();
                }
                return brush;
            }

            return Brushes.Transparent;
        }
Example #30
0
		public void Contains_IntAsKey_Throws ()
		{
			ResourceDictionary rd = new ResourceDictionary ();

			Assert.Throws<ArgumentException> (() => rd.Contains (35));
		}
Example #31
0
		public void Contains_ObejctAsKey_Throws ()
		{
			ResourceDictionary rd = new ResourceDictionary ();

			Assert.Throws<ArgumentException> (() => rd.Contains (new object ()));
		}
        private static object GetTemplate(string key)
        {
            string assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
            string resourcePath = string.Format("{0};component/Templates/Template.xaml", assemblyName);

            var templateDictionary = new ResourceDictionary();
            templateDictionary.Source = new Uri(resourcePath, UriKind.Relative);

            if (!templateDictionary.Contains(key))
            {
                return null;
            }

            object item = templateDictionary[key];
            return item;
        }