コード例 #1
0
        private static void Clone(ResourceDictionary source, ResourceDictionary target)
        {
            foreach (var resourceKeyValue in source)
            {
                if (!target.ContainsKey(resourceKeyValue.Key))
                {
                    target.Add(resourceKeyValue.Key, resourceKeyValue.Value);
                }
            }

            foreach (var dictionary in source.MergedDictionaries)
            {
                var clone = new ResourceDictionary();
                Clone(dictionary, clone);
                target.MergedDictionaries.Add(clone);
            }

            foreach (var dictionaryKeyValue in source.ThemeDictionaries)
            {
                var clone = new ResourceDictionary();
                Clone((ResourceDictionary)dictionaryKeyValue.Value, clone);
                if (!target.ContainsKey(dictionaryKeyValue.Key))
                {
                    target.ThemeDictionaries.Add(dictionaryKeyValue.Key, clone);
                }
            }
        }
コード例 #2
0
        public void When_Has_Default_And_Light()
        {
            UnitTestsApp.App.EnsureApplication();

            var rd   = new ResourceDictionary();
            var dflt = new ResourceDictionary();

            dflt["Blu"] = new SolidColorBrush(Colors.Aqua);
            var light = new ResourceDictionary();

            rd.ThemeDictionaries["Default"] = dflt;
            rd.ThemeDictionaries["Light"]   = light;

            Assert.AreEqual(ApplicationTheme.Light, Application.Current.RequestedTheme);

            Assert.IsFalse(rd.ContainsKey("Blu"));

            var inner      = new ResourceDictionary();
            var lightInner = new ResourceDictionary();

            lightInner["Blu"] = new SolidColorBrush(Colors.DarkSlateBlue);
            inner.ThemeDictionaries["Light"] = lightInner;
            rd.MergedDictionaries.Add(inner);

            Assert.IsTrue(rd.ContainsKey("Blu"));

            Assert.AreEqual(Colors.DarkSlateBlue, (rd["Blu"] as SolidColorBrush).Color);
        }
コード例 #3
0
        public void When_Deep_Merged()
        {
            var rd1 = new ResourceDictionary();

            rd1["Grin"] = new SolidColorBrush(Colors.DarkOliveGreen);

            var rd2 = new ResourceDictionary();

            rd2.MergedDictionaries.Add(rd1);

            var rd3 = new ResourceDictionary();

            rd3.MergedDictionaries.Add(rd2);

            var rd = new ResourceDictionary();

            rd.MergedDictionaries.Add(rd3);

            Assert.IsTrue(rd.ContainsKey("Grin"));

            Assert.IsFalse(rd.ContainsKey("Blu"));

            var retrieved = rd["Grin"];

            Assert.AreEqual(Colors.DarkOliveGreen, ((SolidColorBrush)retrieved).Color);

            rd.TryGetValue("Grin", out var retrieved2);
            Assert.AreEqual(Colors.DarkOliveGreen, ((SolidColorBrush)retrieved2).Color);
        }
コード例 #4
0
        public static Brush ResolveBrushFromResources(string key)
        {
            try
            {
                if (CoreThemeResourceDictionary.ContainsKey(key))
                {
                    if (CoreThemeResourceDictionary[key] is Brush)
                    {
                        return(CoreThemeResourceDictionary[key] as Brush);
                    }
                }

                if (CoreTemplatesResourceDictionary.ContainsKey(key))
                {
                    if (CoreTemplatesResourceDictionary[key] is Brush)
                    {
                        return(CoreTemplatesResourceDictionary[key] as Brush);
                    }
                }
            }
            catch (Exception e)
            {
            }

            return(null);
        }
コード例 #5
0
        public void When_Simple_Add_And_Retrieve_Type_Key()
        {
            var rd = new ResourceDictionary();

            // NOTE: Intentionally using a type outside of Uno.UI to prevent regressions if someone thought to use Type.GetType.
            // See: https://stackoverflow.com/a/1825156/5108631
            // Type.GetType(...) only works when the type is found in either mscorlib.dll or the currently executing assembly.
            rd[typeof(Given_ResourceDictionary)] = nameof(When_Simple_Add_And_Retrieve_Type_Key);

            var retrieved = rd[typeof(Given_ResourceDictionary)];

            Assert.IsTrue(rd.ContainsKey(typeof(Given_ResourceDictionary)));
            Assert.IsFalse(rd.ContainsKey("Uno.UI.Tests.Windows_UI_Xaml.Given_ResourceDictionary"));

            Assert.AreEqual(nameof(When_Simple_Add_And_Retrieve_Type_Key), retrieved);

            rd.TryGetValue(typeof(Given_ResourceDictionary), out var retrieved2);
            Assert.AreEqual(nameof(When_Simple_Add_And_Retrieve_Type_Key), retrieved2);

            var key = rd.Keys.Single();

            Assert.AreEqual(typeof(Given_ResourceDictionary), key);

            foreach (var kvp in rd)
            {
                Assert.AreEqual(typeof(Given_ResourceDictionary), kvp.Key);
            }
        }
コード例 #6
0
        public void When_Enumerated()
        {
            var rd = new ResourceDictionary();

            rd["foot"] = "Boot";
            var inner = new ResourceDictionary();

            inner["hand"] = "Glove";
            rd.MergedDictionaries.Add(inner);
            var def = new ResourceDictionary();

            def["eyes"] = "Sunglasses";
            rd.ThemeDictionaries["Default"] = def;

            var keys = new List <object>();

            foreach (var kvp in rd)
            {
                keys.Add(kvp.Key);
            }

            Assert.IsTrue(keys.Contains("foot"));

            Assert.IsFalse(keys.Contains("hand"));
            Assert.IsTrue(rd.ContainsKey("hand"));

            Assert.IsFalse(keys.Contains("eyes"));
            Assert.IsTrue(rd.ContainsKey("eyes"));
        }
コード例 #7
0
        private static void Add(Expression <Func <Style> > style)
        {
            var styleInfo = style.GetMemberInfo();

            if (!resources.ContainsKey(styleInfo.Name))
            {
                resources.Add(styleInfo.Name, style?.Compile().Invoke());
            }
        }
コード例 #8
0
 public Style this[string index]
 {
     get {
         if (_resources.ContainsKey(index))
         {
             return((Style)_resources[index]);
         }
         return(null);
     }
     set {
         _resources[index] = value;
     }
 }
コード例 #9
0
        Dictionary <char, List <string> > _charToSimpleHighContrastNames; //this dictionary serves to link the first letter of the theme-dependent resource to the simple high contrast names that start with that letter.
        //The objective is to reduce the amount of strings we try to find in the resource (probably a minor improvement in performance but it's something)

        /// <summary>
        /// Tries to find the resourceKey in the Generic.xaml resources of the assembly. Note: the resource currently need to be defined in Project/Themes/generic.xaml
        /// </summary>
        /// <param name="assemblyWhereGenericXamlIsLocated">The assembly where we will look into.</param>
        /// <param name="resourceKey">The resource to find in the Assembly's resources.</param>
        /// <returns>The resource associated with the given key in the given assembly's resources.</returns>
        internal object TryFindResourceInGenericXaml(Assembly assemblyWhereGenericXamlIsLocated, object resourceKey)
        {
            ResourceDictionary resourceDictionary = null;

            if (_assemblyToResourceDictionary.ContainsKey(assemblyWhereGenericXamlIsLocated))
            {
                resourceDictionary = _assemblyToResourceDictionary[assemblyWhereGenericXamlIsLocated];
            }
            else
            {
#if !BRIDGE
                string assemblyName = assemblyWhereGenericXamlIsLocated.GetName().Name;
#else
                string assemblyName = INTERNAL_BridgeWorkarounds.GetAssemblyNameWithoutCallingGetNameMethod(assemblyWhereGenericXamlIsLocated);
#endif
                assemblyName = assemblyName.Replace(" ", "ǀǀ").Replace(".", "ǀǀ");
                string factoryTypeName = MakeTitleCase("ǀǀ" + assemblyName + "ǀǀComponentǀǀThemesǀǀGenericǀǀXamlǀǀFactory");
                Type   resourceDictionaryFactoryType = assemblyWhereGenericXamlIsLocated.GetType(factoryTypeName);
                if (resourceDictionaryFactoryType != null)
                {
                    resourceDictionary = (ResourceDictionary)resourceDictionaryFactoryType.GetMethod("Instantiate").Invoke(null, null);
                    _assemblyToResourceDictionary.Add(assemblyWhereGenericXamlIsLocated, resourceDictionary);
                }
            }

            if (resourceDictionary != null && resourceDictionary.ContainsKey(resourceKey))
            {
                return(resourceDictionary[resourceKey]);
            }

            return(null);
        }
コード例 #10
0
        public void When_Has_Multiple_Themes()
        {
#if !NETFX_CORE
            UnitTestsApp.App.EnsureApplication();
#endif

            var rd    = new ResourceDictionary();
            var light = new ResourceDictionary();
            light["Blu"] = new SolidColorBrush(Colors.LightBlue);
            var dark = new ResourceDictionary();
            dark["Blu"] = new SolidColorBrush(Colors.DarkBlue);

            rd.ThemeDictionaries["Light"] = light;
            rd.ThemeDictionaries["Dark"]  = dark;

            Assert.IsTrue(rd.ContainsKey("Blu"));

            var retrieved1 = rd["Blu"];
            Assert.AreEqual(ApplicationTheme.Light, Application.Current.RequestedTheme);
            Assert.AreEqual(Colors.LightBlue, ((SolidColorBrush)retrieved1).Color);

#if !NETFX_CORE //Not legal on UWP to change theme after app has launched
            try
            {
                Application.Current.SetExplicitRequestedTheme(ApplicationTheme.Dark);
                var retrieved2 = rd["Blu"];
                Assert.AreEqual(Colors.DarkBlue, ((SolidColorBrush)retrieved2).Color);
            }
            finally
            {
                Application.Current.SetExplicitRequestedTheme(ApplicationTheme.Light);
            }
#endif
        }
コード例 #11
0
        public static Style ResolveStyleFromResourceDictionary(ResourceDictionary rd, string key)
        {
            Windows.UI.Xaml.Style st = null;
            try
            {
                if (rd != null)
                {
                    if (rd.ContainsKey(key))
                    {
                        if (rd[key] is Style)
                        {
                            return((Style)rd[key]);
                        }
                    }
                }

                if (CoreThemeResourceDictionary.ContainsKey(key))
                {
                    if (CoreThemeResourceDictionary[key] is Style)
                    {
                        return((Style)CoreThemeResourceDictionary[key]);
                    }
                }
            }
            catch (Exception e)
            {
            }
            return(null);
        }
コード例 #12
0
 public void AddTest1()
 {
     tlog.Debug(tag, $"AddTest1 START");
     try
     {
         ResourceDictionary t2 = new ResourceDictionary();
         Assert.IsNotNull(t2, "null ResourceDictionary");
         t2.Add("AA", "AA");
         var ret = t2.ContainsKey("AA");
         Assert.AreEqual(true, ret, "Should be equal");
         var ret2 = t2["AA"];
         Assert.AreEqual("AA", ret2, "Should be equal");
         Assert.AreEqual(1, t2.Keys.Count, "Should be equal");
         Assert.AreEqual(1, t2.Values.Count, "Should be equal");
         Assert.IsNotNull(t2.GetEnumerator(), "null Enumerator");
         object ss;
         t2.TryGetValue("AA", out ss);
         Assert.AreEqual("AA", ss as string, "Should be equal");
         var ret3 = t2.Remove("AA");
         Assert.True(ret3, "Should be true");
     }
     catch (Exception e)
     {
         Assert.Fail("Caught Exception" + e.ToString());
     }
     tlog.Debug(tag, $"AddTest1 END");
 }
コード例 #13
0
        public override object ProvideValue(IServiceProvider serviceProvider)
#endif
        {
            ServiceProvider serviceProviderAsServiceProvider = (ServiceProvider)serviceProvider;
            Type            targetType;

            if (serviceProviderAsServiceProvider.TargetProperty as DependencyProperty != null)
            {
                targetType = ((DependencyProperty)serviceProviderAsServiceProvider.TargetProperty).PropertyType;
            }
            else
            {
                targetType = null;
            }
            bool   isFirst       = true;
            object elementItself = null;

            foreach (object parentElement in serviceProviderAsServiceProvider.Parents)
            {
                if (isFirst)
                {
                    elementItself = parentElement;
                }
                else
                {
                    ResourceDictionary resourceDictionary = null;
                    if ((resourceDictionary = parentElement as ResourceDictionary) == null)
                    {
                        if (parentElement is FrameworkElement parentAsFrameworkElement)
                        {
                            resourceDictionary = parentAsFrameworkElement.Resources;
                        }
                    }
                    if (resourceDictionary != null && resourceDictionary.ContainsKey(ResourceKey))
                    {
                        object returnElement = resourceDictionary[ResourceKey];
                        if (!object.Equals(returnElement, elementItself))
                        {
                            return(this.EnsurePropertyType(returnElement, targetType));
                        }
                    }
                }
                isFirst = false;
            }
            if (Application.Current.Resources.ContainsKey(ResourceKey))
            {
                return(this.EnsurePropertyType(Application.Current.Resources[ResourceKey], targetType));
            }
            else
            {
                // Look in the built-in resources (eg. "SystemAccentColor"):
                object result = Application.Current.TryFindResource(ResourceKey);
                if (result == null)
                {
                    throw new XamlParseException(string.Format("StaticResource resolve failed: cannot find resource named '{0}' (Note: resource names are case sensitive)", ResourceKey));
                }
                return(this.EnsurePropertyType(result, targetType));
            }
            throw new XamlParseException(string.Format("StaticResource resolve failed: cannot find resource named '{0}' (Note: resource names are case sensitive)", ResourceKey));
        }
コード例 #14
0
        /// <summary>
        /// Searches for the specified resource.
        /// </summary>
        /// <param name="resourceKey">The name of the resource to find.</param>
        /// <returns>
        /// The requested resource object. If the requested resource is not found, a
        /// null reference is returned.
        /// </returns>
        internal object TryFindResource(object resourceKey)
        {
            if (resourceKey is Type)
            {
                Type   resourceKeyAsType = resourceKey as Type;
                object result            = TryFindResourceInGenericXaml(resourceKeyAsType.Assembly, resourceKeyAsType);
                if (result != null)
                {
                    return(result);
                }
            }

            if (Application.Current.Resources.ContainsKey(resourceKey))
            {
                return(Application.Current.Resources[resourceKey]); //I guess we try to find in the local resources first?
            }

            if (_defaultThemeResourcesDictionary == null)
            {
                FillDefaultThemeResources();
            }

            //todo: find what the current theme is.
            //for now we assume the current theme is Light:
            ResourceDictionary lightResourceDictionary = _defaultThemeResourcesDictionary.ThemeDictionaries[LIGHT_RESOURCE_THEME_KEY];

            if (lightResourceDictionary.ContainsKey(resourceKey))
            {
                return(lightResourceDictionary[resourceKey]);
            }

            //if we didn't find the key, try in the HighContrast resources.
            //todo: (Note:) I think the HighContrast resources can be changed outside of the app but that is probably specific to the machine so we'll ignore that for now and simply take the default high contrast values.
            if (_defaultThemeResourcesDictionary.ThemeDictionaries[HIGH_CONSTRAST_RESOURCE_THEME_KEY].ContainsKey(resourceKey))
            {
                return(_defaultThemeResourcesDictionary.ThemeDictionaries[HIGH_CONSTRAST_RESOURCE_THEME_KEY][resourceKey]);
            }

            if (resourceKey is string)
            {
                object result = null;
                result = FindThemeDependentBrush(resourceKey as string);
                if (result != null)
                {
                    return(result);
                }
            }
            //todo: find out whether this is a theme-dependent resource name. See:
            //https://docs.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/xaml-theme-resources#theme-dependent-brushes
            //in this case, deal with it.

            FillDefaultResources();
            if (_defaultResources.ContainsKey(resourceKey))
            {
                return(_defaultResources[resourceKey]);
            }
            return(null);
        }
コード例 #15
0
        public override object ProvideValue(IServiceProvider serviceProvider)
#endif
        {
            if (serviceProvider is ServiceProvider)
            {
                ServiceProvider serviceProviderAsServiceProvider = (ServiceProvider)serviceProvider;
                bool            isFirst       = true;
                object          elementItself = null;
                foreach (Object parentElement in serviceProviderAsServiceProvider.Parents)
                {
                    if (isFirst)
                    {
                        elementItself = parentElement;
                    }
                    else
                    {
                        ResourceDictionary resourceDictionary = null;
                        if (parentElement is ResourceDictionary)
                        {
                            resourceDictionary = (ResourceDictionary)parentElement;
                        }
                        else if (parentElement is FrameworkElement)
                        {
                            resourceDictionary = ((FrameworkElement)parentElement).Resources;
                        }
                        if (resourceDictionary != null && resourceDictionary.ContainsKey(ResourceKey))
                        {
                            object returnElement = resourceDictionary[ResourceKey];
                            if (returnElement != elementItself)
                            {
                                return(returnElement);
                            }
                        }
                    }
                    isFirst = false;
                }
                if (Application.Current.Resources != null && Application.Current.Resources.ContainsKey(ResourceKey))
                {
                    return(Application.Current.Resources[ResourceKey]);
                }
                else
                {
                    // Look in the built-in resources (eg. "SystemAccentColor"):
                    object result = Application.Current.TryFindResource(ResourceKey);
                    if (result == null)
                    {
                        throw new XamlParseException(string.Format("StaticResource resolve failed: cannot find resource named '{0}' (Note: resource names are case sensitive)", ResourceKey));
                    }
                    return(result);
                }
                throw new XamlParseException(string.Format("StaticResource resolve failed: cannot find resource named '{0}' (Note: resource names are case sensitive)", ResourceKey));
            }
            else
            {
                throw new SystemException("StaticResourceExtension.ProvideValue failed: the service provider is not of the expected type. Please contact support.");
            }
        }
コード例 #16
0
        Dictionary <char, List <string> > _charToSimpleHighContrastNames; //this dictionary serves to link the first letter of the theme-dependent resource to the simple high contrast names that start with that letter.
        //The objective is to reduce the amount of strings we try to find in the resource (probably a minor improvement in performance but it's something)

        /// <summary>
        /// Tries to find the resourceKey in the Generic.xaml resources of the assembly. Note: the resource currently need to be defined in Project/Themes/generic.xaml
        /// </summary>
        /// <param name="assemblyWhereGenericXamlIsLocated">The assembly where we will look into.</param>
        /// <param name="resourceKey">The resource to find in the Assembly's resources.</param>
        /// <returns>The resource associated with the given key in the given assembly's resources.</returns>
        internal object TryFindResourceInGenericXaml(Assembly assemblyWhereGenericXamlIsLocated, object resourceKey)
        {
            ResourceDictionary resourceDictionary = null;

            if (_assemblyToResourceDictionary.ContainsKey(assemblyWhereGenericXamlIsLocated))
            {
                resourceDictionary = _assemblyToResourceDictionary[assemblyWhereGenericXamlIsLocated];
            }
            else
            {
#if !BRIDGE
                string assemblyName = assemblyWhereGenericXamlIsLocated.GetName().Name;
                // todo: instead of the following if, make it so that the Core project can generate the .g.cs files by itself (JSIL version, Bridge works fine) instead of relying on an external project (called DotNetForHtml5.Core.Styles). Note: given what the name of the assembly is, it should still be shortened to remove everything after the first comma.
                //Fixing the assemblyName so that the default styles can be found (the generic.xaml file that contains the default styles is located in a different project with a different namespace):
                if (assemblyName == "SLMigration.CSharpXamlForHtml5" || assemblyName == "CSharpXamlForHtml5" ||
                    assemblyName == "SLMigration.CSharpXamlForHtml5, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" || assemblyName == "CSharpXamlForHtml5, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")
                {
                    assemblyName = "DotNetForHtml5.Core.Styles"; //Note: this is the name of the assembly where the default styles are defined (project DotNetForHtml5.Core.Styles in the DotNetForHtml5 solution).
                }
#else
                string assemblyName = INTERNAL_BridgeWorkarounds.GetAssemblyNameWithoutCallingGetNameMethod(assemblyWhereGenericXamlIsLocated);
#endif
                assemblyName = assemblyName.Replace(" ", "ǀǀ").Replace(".", "ǀǀ");
                string factoryTypeName = MakeTitleCase("ǀǀ" + assemblyName + "ǀǀComponentǀǀThemesǀǀGenericǀǀXamlǀǀFactory");
                Type   resourceDictionaryFactoryType = assemblyWhereGenericXamlIsLocated.GetType(factoryTypeName);
#if CSHTML5BLAZOR
                if (resourceDictionaryFactoryType == null)
                {
                    if (assemblyName == "OpenSilver") //We do this part because OpenSilver uses the generic.xaml.g.cs of the CSHTML5 Migration edition which in consequence has a different namespace than it would have if it was directly defined as xaml in OpenSilver.
                    {
                        assemblyName    = "Cshtml5ǀǀMigration";
                        factoryTypeName = MakeTitleCase("ǀǀ" + assemblyName + "ǀǀComponentǀǀThemesǀǀGenericǀǀXamlǀǀFactory");
                        resourceDictionaryFactoryType = assemblyWhereGenericXamlIsLocated.GetType(factoryTypeName);
                    }
                    else if (assemblyName == "OpenSilverǀǀUwpCompatible") //We do this part because OpenSilver uses the generic.xaml.g.cs of the CSHTML5 Migration edition which in consequence has a different namespace than it would have if it was directly defined as xaml in OpenSilver.
                    {
                        assemblyName    = "Cshtml5";
                        factoryTypeName = MakeTitleCase("ǀǀ" + assemblyName + "ǀǀComponentǀǀThemesǀǀGenericǀǀXamlǀǀFactory");
                        resourceDictionaryFactoryType = assemblyWhereGenericXamlIsLocated.GetType(factoryTypeName);
                    }
                }
#endif

                if (resourceDictionaryFactoryType != null)
                {
                    resourceDictionary = (ResourceDictionary)resourceDictionaryFactoryType.GetMethod("Instantiate").Invoke(null, null);
                    _assemblyToResourceDictionary.Add(assemblyWhereGenericXamlIsLocated, resourceDictionary);
                }
            }

            if (resourceDictionary != null && resourceDictionary.ContainsKey(resourceKey))
            {
                return(resourceDictionary[resourceKey]);
            }

            return(null);
        }
コード例 #17
0
        private DataTemplate SearchTemplate(ResourceDictionary dictionary, string key)
        {
            if (dictionary.ContainsKey(key))
            {
                return(dictionary[key] as DataTemplate);
            }

            return(null);
        }
コード例 #18
0
        public void When_Accessing_System_Resource()
        {
            var rd = new ResourceDictionary();

            Assert.IsTrue(rd.ContainsKey("SystemAltHighColor"));
            var systemColor = (Color)rd["SystemAltHighColor"];

            Assert.AreEqual(Colors.White, systemColor);
        }
コード例 #19
0
        // Get image source using Id from merged resource dictionaries
        private static T GetResourceDictionaryById <T>(string dictionaryId, ref Boolean found, ResourceDictionary dictionary = null) //where T : class
        {
            T result = default(T);

            if (dictionary == null)
            {
                dictionary = App.Current.Resources;
            }


            if (dictionary.ContainsKey(dictionaryId) || dictionary.Count > 0)
            {
                try
                {
                    var obj = dictionary[dictionaryId];
                    if (obj is T)
                    {
                        found  = true;
                        result = (T)obj;
                    }
                    else
                    {
                        if (obj is Xamarin.Forms.OnPlatform <T> onPlatform)
                        {
                            foreach (On on in onPlatform.Platforms)
                            {
                                if (on.Platform.Contains(Device.RuntimePlatform))
                                {
                                    found  = true;
                                    result = (T)Convert.ChangeType(on.Value, typeof(T));
                                    break;
                                }
                            }
                        }
                    }
                }
                catch { }
            }

            if (!found)
            {
                // Check on child merged dictionaries
                if (dictionary.MergedDictionaries?.Count > 0)
                {
                    List <ResourceDictionary> list = dictionary.MergedDictionaries.ToList();
                    for (int index = 0; index < dictionary.MergedDictionaries.Count; index++)
                    {
                        result = GetResourceDictionaryById <T>(dictionaryId, ref found, list[index]);
                        if (found)
                        {
                            break;
                        }
                    }
                }
            }
            return(result);
        }
コード例 #20
0
        public static ElementTheme UpdateColorThemeResources(string rdTemplateXaml)
        {
            ElementTheme theme = ElementTheme.Dark;
            Dictionary <string, Color> colors = new Dictionary <string, Color>();

            try
            {
                var rdn = (ResourceDictionary)XamlReader.Load(rdTemplateXaml);
                if (rdn != null)
                {
                    if (rdn.Keys != null)
                    {
                        foreach (var ky in rdn.Keys)
                        {
                            if (rdn[ky] is SolidColorBrush)
                            {
                                colors.Add((string)ky, ((SolidColorBrush)rdn[ky]).Color);
                            }
                            else if (ky.ToString() == "SkinTheme")
                            {
                                if (rdn[ky] is ElementTheme)
                                {
                                    theme = (ElementTheme)rdn[ky];
                                }
                            }
                        }
                    }
                }

                ResourceDictionary rd = Application.Current.Resources.MergedDictionaries[0].MergedDictionaries[0].MergedDictionaries[0];

                foreach (string ky in colors.Keys)
                {
                    if (rd.ContainsKey(ky))
                    {
                        if (rd[ky] is SolidColorBrush)
                        {
                            (rd[ky] as SolidColorBrush).Color = colors[ky];
                        }
                    }
                }


                try
                {
                    rd["SkinTheme"] = theme;
                }
                catch (Exception e)
                {
                    string p = e.Message;
                }
            }
            catch (Exception e)
            {
            }
            return(theme);
        }
コード例 #21
0
        private void AddImage(bool broken, bool placeholder, bool round = false)
        {
            ImageExBase newImage = null;

            if (round)
            {
                #pragma warning disable CS0618 // Type or member is obsolete
                newImage = new RoundImageEx
                {
                };
                #pragma warning restore CS0618 // Type or member is obsolete

                if (resources?.ContainsKey("RoundStyle") == true)
                {
                    newImage.Style = resources["RoundStyle"] as Style;
                }
            }
            else
            {
                newImage = new ImageEx();

                if (resources?.ContainsKey("RectangleStyle") == true)
                {
                    newImage.Style = resources["RectangleStyle"] as Style;
                }
            }

            newImage.Source = broken ? photos[imageIndex].Thumbnail + "broken" : photos[imageIndex].Thumbnail;

            if (placeholder)
            {
                newImage.PlaceholderSource = new BitmapImage(new Uri("ms-appx:///Assets/Photos/ImageExPlaceholder.jpg"));
            }

            container?.Children?.Add(newImage);

            // Move to next image
            imageIndex++;
            if (imageIndex >= photos.Count)
            {
                imageIndex = 0;
            }
        }
コード例 #22
0
 public static object GetOrNull(this ResourceDictionary dictionary, string key)
 {
     if (dictionary.ContainsKey(key))
     {
         return(dictionary[key]);
     }
     else
     {
         return(null);
     }
 }
コード例 #23
0
        private void OverrideFlyoutResources(Styles styles, bool accent = false)
        {
            var fromColorKey = accent ? "MahApps.Colors.Highlight" : "MahApps.Colors.Flyout";
            var item         = styles.GetThemeStyle();

            styles.Remove(item);

            ResourceDictionary resources = (item.Loaded as Style).Resources as ResourceDictionary;

            var fromColor = (Color)item.FindResource(fromColorKey);

            resources["MahApps.Colors.White"]  = fromColor;
            resources["MahApps.Colors.Flyout"] = fromColor;

            var newBrush = new SolidColorBrush(fromColor);

            //newBrush.Freeze();
            resources["MahApps.Brushes.Flyout.Background"]  = newBrush;
            resources["MahApps.Brushes.Control.Background"] = newBrush;
            resources["MahApps.Brushes.White"]             = newBrush;
            resources["MahApps.Brushes.WhiteColor"]        = newBrush;
            resources["MahApps.Brushes.DisabledWhite"]     = newBrush;
            resources["MahApps.Brushes.Window.Background"] = newBrush;
            resources["ThemeBackgroundBrush"] = newBrush;

            if (accent)
            {
                fromColor = (Color)resources["MahApps.Colors.IdealForeground"];
                newBrush  = new SolidColorBrush(fromColor);
                //    newBrush.Freeze();
                resources["MahApps.Brushes.Flyout.Foreground"] = newBrush;
                resources["MahApps.Brushes.Text"]       = newBrush;
                resources["MahApps.Brushes.Label.Text"] = newBrush;

                if (resources.ContainsKey("MahApps.Colors.AccentBase"))
                {
                    fromColor = (Color)resources["MahApps.Colors.AccentBase"];
                }
                else
                {
                    var accentColor = (Color)resources["MahApps.Colors.Accent"];
                    fromColor = Color.FromArgb(255, accentColor.R, accentColor.G, accentColor.B);
                }
                newBrush = new SolidColorBrush(fromColor);
                //    newBrush.Freeze();
                resources["MahApps.Colors.Highlight"]  = fromColor;
                resources["MahApps.Brushes.Highlight"] = newBrush;
                resources["MahApps.Brushes.Highlight"] = newBrush;
            }

            styles.Add(item);

            //resources.EndInit();
        }
コード例 #24
0
 public static void PutMany(this ResourceDictionary dict, ResourceDictionary source)
 {
     foreach (var entry in source.AsEnumerable())
     {
         if (dict.ContainsKey(entry.Key))
         {
             dict.Remove(entry.Key);
         }
         dict.Add(entry.Key, entry.Value);
     }
 }
コード例 #25
0
        private void OnAddBladeButtonClicked(object sender, RoutedEventArgs e)
        {
            if (resources?.ContainsKey("BladeStyle") == true)
            {
                BladeItem bladeItem = new BladeItem()
                {
                    Style = resources["BladeStyle"] as Style
                };

                bladeView?.Items?.Add(bladeItem);
            }
        }
コード例 #26
0
        public TransactionsPageViewModel()
        {
            _service = IoC.Resolve <ITransactionService>();

            var resource = new ResourceDictionary()
            {
                Source = new Uri("ms-appx:///Styles/Custom.xaml")
            };

            if (resource.ContainsKey("IncomeColorBrush"))
            {
                _incomeBrush   = resource["IncomeColorBrush"] as SolidColorBrush;
                _expensesBrush = resource["ExpensesColorBrush"] as SolidColorBrush;
            }
        }
コード例 #27
0
        public void When_Has_Inactive_Theme()
        {
#if !NETFX_CORE
            UnitTestsApp.App.EnsureApplication();
#endif
            var rd   = new ResourceDictionary();
            var dark = new ResourceDictionary();
            dark["Blu"] = new SolidColorBrush(Colors.DarkBlue);

            rd.ThemeDictionaries["Dark"] = dark;

            Assert.AreEqual(ApplicationTheme.Light, Application.Current.RequestedTheme);
            Assert.IsFalse(rd.ContainsKey("Blu"));
            ;
        }
コード例 #28
0
        public void When_Simple_Add_And_Retrieve()
        {
            var rd = new ResourceDictionary();

            rd["Grin"] = new SolidColorBrush(Colors.DarkOliveGreen);

            var retrieved = rd["Grin"];

            Assert.IsTrue(rd.ContainsKey("Grin"));

            Assert.AreEqual(Colors.DarkOliveGreen, ((SolidColorBrush)retrieved).Color);

            rd.TryGetValue("Grin", out var retrieved2);
            Assert.AreEqual(Colors.DarkOliveGreen, ((SolidColorBrush)retrieved2).Color);
        }
コード例 #29
0
        private bool TryGetResource(ResourceDictionary rd, string key, out DataTemplate template)
        {
            if (null == rd)
            {
                throw new ArgumentNullException(nameof(rd));
            }

            if (null == key)
            {
                throw new ArgumentNullException(nameof(key));
            }

            template = rd.ContainsKey(key) ? rd[key] as DataTemplate : null;

            return(null != template);
        }
コード例 #30
0
        public void When_Created_From_Source_In_Codebehind()
        {
            var rd = new ResourceDictionary {
                Source = new Uri("ms-appx:///Uno.UI.Tests.ViewLibrary/Themes/More/Test_Dictionary_Abs.xaml")
            };

            AssertEx.AssertContainsColorBrushResource(rd, "BituminousColorBrush", Colors.SlateGray);

            var rd2 = new ResourceDictionary {
                Source = new Uri("ms-appx:///Uno.UI.Tests.ViewLibrary/Themes/More/Test_Dictionary_Abs.xaml")
            };

            rd2.Remove("BituminousColorBrush");
            Assert.IsFalse(rd2.ContainsKey("BituminousColorBrush"));
            Assert.IsTrue(rd.ContainsKey("BituminousColorBrush"));
        }
コード例 #31
0
ファイル: Splash.xaml.cs プロジェクト: noriike/xaml-106136
        public static void SetupTheme(bool reload = true)
        {
            var _ColorString = StorageHelper.GetSetting(Contracts.Settings.PrimaryColor, Contracts.Settings.DefaultColor);

            Uri _Path = null;
            if (_ColorString.Equals(Windows.UI.Colors.Red.ToString()))
                _Path = new Uri("ms-appx:/Styles/CustomStyles.Red.xaml");
            else if (_ColorString.Equals(Windows.UI.Colors.Green.ToString()))
                _Path = new Uri("ms-appx:/Styles/CustomStyles.Green.xaml");
            else if (_ColorString.Equals(Windows.UI.Colors.Blue.ToString()))
                _Path = new Uri("ms-appx:/Styles/CustomStyles.Blue.xaml");
            else if (_ColorString.Equals(Windows.UI.Colors.Orange.ToString()))
                _Path = new Uri("ms-appx:/Styles/CustomStyles.Orange.xaml");

            var _Standard = new ResourceDictionary { Source = new Uri("ms-appx:/Styles/StandardStyles.xaml") };
            var _Custom = new ResourceDictionary { Source = _Path };
            var _Main = new ResourceDictionary { MergedDictionaries = { _Standard, _Custom } };
            foreach (var item in App.Current.Resources)
            {
                if (!_Main.ContainsKey(item.Key))
                    _Main.Add(item);
            }
            App.Current.Resources = _Main;

            // refresh the style immediately
            if (reload)
                Services.Navigation.Reload();
        }