public BasicStyleCodePage() { Resources = new ResourceDictionary { { "buttonStyle", new Style(typeof(Button)) { Setters = { new Setter { Property = View.HorizontalOptionsProperty, Value = LayoutOptions.Center }, new Setter { Property = View.VerticalOptionsProperty, Value = LayoutOptions.CenterAndExpand }, new Setter { Property = Button.BorderWidthProperty, Value = 3 }, new Setter { Property = Button.TextColorProperty, Value = Color.Red }, new Setter { Property = Button.FontSizeProperty, Value = Device.GetNamedSize(NamedSize.Large, typeof(Button)) } } } } }; Content = new StackLayout { Children = { new Button { Text = " Do this! ", Style = (Style)Resources["buttonStyle"] }, new Button { Text = " Do that! ", Style = (Style)Resources["buttonStyle"] }, new Button { Text = " Do the other thing! ", Style = (Style)Resources["buttonStyle"] } } }; }
/// <summary> /// Initializes a new instance of the Theme class. /// </summary> /// <param name="themeAssembly"> /// Assembly with the embedded resource containing the theme to apply. /// </param> /// <param name="themeResourceName"> /// Name of the embedded resource containing the theme to apply. /// </param> protected Theme(Assembly themeAssembly, string themeResourceName) : this() { if (themeAssembly == null) { throw new ArgumentNullException("themeAssembly"); } // Get the resource stream for the theme. using (Stream stream = themeAssembly.GetManifestResourceStream(themeResourceName)) { if (stream == null) { throw new ResourceNotFoundException( string.Format( CultureInfo.CurrentCulture, Properties.Resources.Theme_ResourceNotFound, themeResourceName), new Uri(themeResourceName, UriKind.Relative)); } // Load the theme ThemeResources = LoadThemeResources(stream, Resources); } }
public static void LoadSettings() { // Load all available themes Themes = new List<Theme>(); var blue = new ResourceDictionary { Source = new Uri("ms-appx:///Themes/Blue.xaml") }; var blueTheme = new Theme { Resource = blue }; var black = new ResourceDictionary { Source = new Uri("ms-appx:///Themes/Black.xaml") }; var blackTheme = new Theme { Resource = black }; var red = new ResourceDictionary { Source = new Uri("ms-appx:///Themes/Red.xaml") }; var redTheme = new Theme { Resource = red }; Themes.Add(blueTheme); Themes.Add(blackTheme); Themes.Add(redTheme); // Load Theme var setTheme = new Theme(); var localSettings = ApplicationData.Current.LocalSettings; var theme = localSettings.Values["Theme"]; if (theme == null) { // Theme not set so default to Black var resource = new ResourceDictionary { Source = new System.Uri("ms-appx:///Themes/Black.xaml") }; setTheme.Resource = resource; } else { var resource = new ResourceDictionary { Source = new System.Uri(theme.ToString()) }; setTheme.Resource = resource; } Theme = setTheme; }
public App() { _pages = new Dictionary<ExampleViewCellModel, Type> { {new ExampleViewCellModel {Title = "Button Animation"}, typeof (ButtonPage)}, {new ExampleViewCellModel {Title = "Paper Button Animation"}, typeof (PaperButtonPage)}, {new ExampleViewCellModel {Title = "Password Indicator Animation"}, typeof (PasswordIndicatorPage)} }; var list = new ListView { ItemTemplate = new DataTemplate(typeof (ExampleViewCell)), ItemsSource = _pages.Keys.ToArray(), RowHeight = 50 }; list.ItemSelected += List_ItemSelected; var rootPage = new ContentPage { Title = "Forms Animation Examples", Content = list }; Resources = new ResourceDictionary(); SetGlobalStyles(); MainPage = new NavigationPage(rootPage); }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="args">Details about the launch request and process.</param> async protected override void OnLaunched(LaunchActivatedEventArgs args) { // based upon the "use app branding" load in new themes ResourceDictionary appBranding = new ResourceDictionary(); appBranding.Source = new System.Uri("ms-appx:///DesertBranding.xaml"); this.Resources.MergedDictionaries.Add(appBranding); this.LaunchArgs = args; Frame rootFrame = null; if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Do an asynchronous restore await SuspensionManager.RestoreAsync(); } if (Window.Current.Content == null) { rootFrame = new Frame(); rootFrame.Navigate(typeof(MainPage)); Window.Current.Content = rootFrame; } Window.Current.Activate(); }
public SimpleTriggerPage () { var t = new Trigger (typeof(Entry)); t.Property = Entry.IsFocusedProperty; t.Value = true; t.Setters.Add (new Setter {Property = Entry.ScaleProperty, Value = 1.5 } ); var s = new Style (typeof(Entry)); s.Setters.Add (new Setter { Property = AnchorXProperty, Value = 0} ); s.Triggers.Add (t); Resources = new ResourceDictionary (); Resources.Add (s); Padding = new Thickness (20, 50, 120, 0); Content = new StackLayout { Spacing = 20, Children = { new Entry { Placeholder = "enter name" }, new Entry { Placeholder = "enter address" }, new Entry { Placeholder = "enter city and name" }, } }; }
public IResourceDictionary GetSystemResources() { _dictionary = new ResourceDictionary(); UpdateStyles(); return _dictionary; }
public ResourceViewModel(object key, object resource, ResourceDictionary dictionary) : base(null) { this.Key = key; this.Name = key.ToString(); _dictionary = dictionary; this.Value = resource; this.PropertyType = _value.GetType(); }
private void ApplyTheme(Theme theme) { var uri = new Uri($"ms-appx:///Styles/{theme}.xaml", UriKind.Absolute); var resourceDictionary = new ResourceDictionary { Source = uri }; Resources.MergedDictionaries.Add(resourceDictionary); }
public CustomEasingSwellPage() { Resources = new ResourceDictionary(); Resources.Add("customEase", new Easing(t => -6 * t * t + 7 * t)); InitializeComponent(); }
public DynamicVsStaticCodePage() { Padding = new Thickness(5, 0); // Create resource dictionary and add item. Resources = new ResourceDictionary { { "currentDateTime", "Not actually a DateTime" } }; Content = new StackLayout { Children = { new Label { Text = "StaticResource on Label.Text:", VerticalOptions = LayoutOptions.EndAndExpand, FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)) }, new Label { Text = (string)Resources["currentDateTime"], VerticalOptions = LayoutOptions.StartAndExpand, HorizontalTextAlignment = TextAlignment.Center, FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)) }, new Label { Text = "DynamicResource on Label.Text:", VerticalOptions = LayoutOptions.EndAndExpand, FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)) } } }; // Create the final label with the dynamic resource. Label label = new Label { VerticalOptions = LayoutOptions.StartAndExpand, HorizontalTextAlignment = TextAlignment.Center, FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)) }; label.SetDynamicResource(Label.TextProperty, "currentDateTime"); ((StackLayout)Content).Children.Add(label); // Start the timer going. Device.StartTimer(TimeSpan.FromSeconds(1), () => { Resources["currentDateTime"] = DateTime.Now.ToString(); return true; }); }
/// <summary> /// 使用在导航过程中传递的内容填充页。在从以前的会话 /// 重新创建页时,也会提供任何已保存状态。 /// </summary> /// <param name="navigationParameter">最初请求此页时传递给 /// <see cref="Frame.Navigate(Type, Object)"/> 的参数值。 /// </param> /// <param name="pageState">此页在以前会话期间保留的状态 /// 字典。首次访问页面时为 null。</param> protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState) { // TODO: 创建适用于问题域的合适数据模型以替换示例数据 ResourceDictionary res = new ResourceDictionary(); res.Source = new Uri("ms-appx:///Common/StandardStyles.xaml", UriKind.Absolute); SampleDataSource.Resources = res; var sampleDataGroups = SampleDataSource.GetGroups((String)navigationParameter); this.DefaultViewModel["Groups"] = sampleDataGroups; }
public static void SetMergedDictionaries(DependencyObject d, ResourceDictionary dictionary) { if(d == null) { throw new ArgumentNullException("d"); } d.SetValue(MergedDictionariesProperty, dictionary); }
/// <summary> /// Makes a shallow copy of the specified ResourceDictionary. /// </summary> /// <param name="dictionary">ResourceDictionary to copy.</param> /// <returns>Copied ResourceDictionary.</returns> public static ResourceDictionary ShallowCopy(this ResourceDictionary dictionary) { ResourceDictionary clone = new ResourceDictionary(); foreach (object key in dictionary.Keys) { clone.Add(key, dictionary[key]); } return clone; }
void ChangeTheme(Uri theme) { var t = new ResourceDictionary { Source = theme }; var r = new ResourceDictionary { MergedDictionaries = { t } }; App.Current.Resources = r; var f = (Window.Current.Content as Frame); f.Navigate(f.Content.GetType()); f.GoBack(); }
public SampleDataCommon(String uniqueId, String title, String subtitle, String imageItemsPath, String imageGroupsPath, String description, ResourceDictionary res, String brushPath) { this._uniqueId = uniqueId; this._title = title; this._subtitle = subtitle; this._description = description; this._imageItemsPath = imageItemsPath; this._imageGroupsPath = imageGroupsPath; this._resources = res; this._brushPath = brushPath; }
public MyPage() { Resources = new ResourceDictionary(); Resources.Add("primaryGreen", Color.FromHex("91CA47")); Resources.Add("primaryDarkGreen", Color.FromHex("6FA22E")); var nav = new NavigationPage(new AAloggerUpSwipeView()); nav.BarTextColor = Color.Blue; MainPage = nav; }
private void Button_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) { ResourceDictionary current = App.Current.Resources.MergedDictionaries.FirstOrDefault(); if (current != null) { App.Current.Resources.MergedDictionaries.Remove(current); } var blue = new ResourceDictionary(); blue.Source = new System.Uri("ms-appx:///Themes/Blue.xaml"); App.Current.Resources.MergedDictionaries.Add(blue); }
public App () { Resources = new ResourceDictionary (); Resources.Add ("primaryGreen", Color.FromHex("91CA47")); Resources.Add ("primaryDarkGreen", Color.FromHex ("6FA22E")); var nav = new NavigationPage (new TodoListPage ()); nav.BarBackgroundColor = (Color)App.Current.Resources["primaryGreen"]; nav.BarTextColor = Color.White; MainPage = nav; }
public App() { #region Style var contentPageStyle = new Style(typeof(ContentPage)) { Setters = { new Setter { Property = ContentPage.BackgroundColorProperty, Value = Constants.palette.primary }, } }; var labelStyle = new Style(typeof(Label)) { Setters = { new Setter { Property = Label.TextColorProperty, Value = Constants.palette.primary_text }, } }; var editorStyle = new Style(typeof(Editor)) { Setters = { new Setter { Property = Editor.TextColorProperty, Value = Constants.palette.primary_text }, new Setter { Property = Editor.BackgroundColorProperty, Value = Constants.palette.primary_light }, } }; var buttonStyle = new Style(typeof(Button)) { Setters = { new Setter { Property = Button.TextColorProperty, Value = Constants.palette.primary_text }, new Setter { Property = Button.BackgroundColorProperty, Value = Constants.palette.primary_light }, } }; var switchStyle = new Style(typeof(Switch)) { Setters = { new Setter { Property = Switch.BackgroundColorProperty, Value = Constants.palette.primary_light }, } }; Resources = new ResourceDictionary(); Resources.Add("contentPageStyle", contentPageStyle); Resources.Add("labelStyle", labelStyle); Resources.Add("editorStyle", editorStyle); #endregion // The root page of your application mainPage = new NavigationPage(new mainPage()) { BarBackgroundColor = Constants.palette.primary_dark, BarTextColor = Constants.palette.icons, Title = "VOCAB MASTER", }; MainPage = mainPage; }
/// <summary> /// Sets the application resource dictionary. /// </summary> /// <param name="uri">The uri of the resource dictionary.</param> private static void SetApplicationResourceDictionaryUri(Uri uri) { if (uri == null) { Application.Current.Resources.MergedDictionaries.Clear(); } else { ResourceDictionary resourceDictionary = new ResourceDictionary { Source = uri }; Application.Current.Resources.MergedDictionaries.Add(resourceDictionary); } }
internal void LoadContent(ContentManager content, string[] texturePaths, string[] fontPaths, string[] scenePaths) { textures = new ResourceDictionary<Texture2D>(new ContentResourceLoader<Texture2D>(content)); fonts = new ResourceDictionary<SpriteFont>(new ContentResourceLoader<SpriteFont>(content)); scenes = new ResourceDictionary<Scene>(new SceneResourceLoader()); for (int i = 0; i < texturePaths.Length; i++) textures.Load(texturePaths[i]); for (int i = 0; i < fontPaths.Length; i++) fonts.Load(fontPaths[i]); for (int i = 0; i < scenePaths.Length; i++) scenes.Load(scenePaths[i]); }
public VisualTreeView() { this.InitializeComponent(); var treeViewMouseResources = new ResourceDictionary { Source = new Uri("ms-appx:///WinRTXamlToolkit/Controls/TreeView/TreeViewMouse.xaml") }; this.Resources.MergedDictionaries.Add(treeViewMouseResources); this.treeView.Style = (Style)treeViewMouseResources["MouseTreeViewStyle"]; this.DataContext = VisualTreeViewModel.Instance; }
public Agenda() { resources = Resources; foreach (var classInstance in Data.classInstances) upcomingList.Add(new DisplayClass(classInstance)); foreach (var taskInstance in Data.tasks) upcomingList.Add(new DisplayClass(taskInstance)); upcomingList = upcomingList.OrderBy(x => x.taskInstance == null ? Extensions.WhenIsNext(x.classInstance, DateTime.Now) : x.taskInstance.deadline).ToList(); this.InitializeComponent(); }
public App() { // The root page of your application MainPage = new NavigationPage(new Inicio()); // Amostra grátis de Styles var btnStyle = new Style(typeof(Button)); btnStyle.Setters.Add(new Setter() { Property = Button.BackgroundColorProperty, Value = Color.Red }); btnStyle.Setters.Add(new Setter() { Property = Button.TextColorProperty, Value = Color.White }); Resources = new ResourceDictionary(); Resources.Add(btnStyle); }
protected DataTemplate Find(ResourceDictionary resource, string key) { var template = resource.FirstOrDefault(o => o.Key.ToString() == key).Value as DataTemplate; if (template != null) return template; foreach (var merge in resource.MergedDictionaries) { template = Find(merge, key); if (template != null) return template; } return null; }
public CustomListView() { this.InitializeComponent(); properties = new Properties(); DataContext = properties; _resources = App.Current.Resources; LoadImage(); Windows.UI.Core.SystemNavigationManager.GetForCurrentView().BackRequested += (s, a) => { if (Frame.CanGoBack) { Frame.GoBack(); a.Handled = true; } }; }
public IResourceDictionary GetSystemResources() { Windows.UI.Xaml.ResourceDictionary windowsResources = Windows.UI.Xaml.Application.Current.Resources; var resources = new ResourceDictionary(); resources[Device.Styles.TitleStyleKey] = GetStyle("HeaderTextBlockStyle"); resources[Device.Styles.SubtitleStyleKey] = GetStyle("SubheaderTextBlockStyle"); resources[Device.Styles.BodyStyleKey] = GetStyle("BodyTextBlockStyle"); resources[Device.Styles.CaptionStyleKey] = GetStyle("CaptionTextBlockStyle"); #if WINDOWS_UWP resources[Device.Styles.ListItemTextStyleKey] = GetStyle("BaseTextBlockStyle"); #else resources[Device.Styles.ListItemTextStyleKey] = GetStyle("TitleTextBlockStyle"); #endif resources[Device.Styles.ListItemDetailTextStyleKey] = GetStyle("BodyTextBlockStyle"); return resources; }
// TODO: I am using an async void, bad programmer public static async void Inject() { if (_injected) return; _injected = true; await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // Let's inject our toast into frame using a special Frame template defined in FrameStyle.xaml var frameStyleRd = new ResourceDictionary(); var frame = (Frame)Window.Current.Content; frameStyleRd.Source = new Uri("ms-appx:///FrameStyle.xaml", UriKind.Absolute); Application.Current.Resources.MergedDictionaries.Add(frameStyleRd); frame.Style = Application.Current.Resources["MainFrameStyle"] as Style; }); }
internal ResourcesChangeInfo(ResourceDictionary oldDictionary, ResourceDictionary newDictionary) { this.oldDictionaries = null; if (oldDictionary != null) { this.oldDictionaries = new List<ResourceDictionary>(1); this.oldDictionaries.Add(oldDictionary); } this.newDictionaries = null; if (newDictionary != null) { this.newDictionaries = new List<ResourceDictionary>(1); this.newDictionaries.Add(newDictionary); } this.key = null; this.container = null; this.flags = (ResourcesChangeInfo.PrivateFlags)0; }
public static void SetTheme(bool android, ResourceDictionary resources) { SetThemeStyle(GetTheme(android), resources); }
void AddResourceDictionary(string source) { ResourceDictionary resourceDictionary = Application.LoadComponent(new Uri(source, UriKind.Relative)) as ResourceDictionary; this.Resources.MergedDictionaries.Add(resourceDictionary); }
public static void AddXamlResource(this ResourceDictionary dictionary, string xamlFileName, string xamlFileAssemblyName) { dictionary.MergedDictionaries.Add(CreateResourceDictionaryFromFile(xamlFileName, xamlFileAssemblyName)); }
/// <summary> /// Class constructor /// </summary> public PluginModelBase() { this.mResources = this.LoadResourceDictionary("/SharedResources.xaml"); }
public static ResourceDictionary GetSystemAccent() { SolidColorBrush AccentBaseColorBrush = (SolidColorBrush)SystemParameters.WindowGlassBrush; Double dY = AccentBaseColorBrush.Color.R * 0.299 + AccentBaseColorBrush.Color.G * 0.587 + AccentBaseColorBrush.Color.B * 0.114; if (dY >= 192 || dY < 50) { return(null); } ResourceDictionary rd = new ResourceDictionary(); Color AccentBaseColor = AccentBaseColorBrush.Color; Color HighlightColor = Color.Multiply(AccentBaseColor, 0.73f); HighlightColor.A = 0xFF; SolidColorBrush HighlightBrush = new SolidColorBrush(HighlightColor); Color AccentColor = AccentBaseColor; AccentColor.A = 0xCC; SolidColorBrush AccentColorBrush = new SolidColorBrush(AccentColor); Color AccentColor2 = AccentBaseColor; AccentColor2.A = 0x99; SolidColorBrush AccentColorBrush2 = new SolidColorBrush(AccentColor2); Color AccentColor3 = AccentBaseColor; AccentColor3.A = 0x66; SolidColorBrush AccentColorBrush3 = new SolidColorBrush(AccentColor3); Color AccentColor4 = AccentBaseColor; AccentColor4.A = 0x33; SolidColorBrush AccentColorBrush4 = new SolidColorBrush(AccentColor4); //Color AccentColor= HighlightColor, rd.Add("HighlightColor", HighlightColor); rd.Add("AccentBaseColor", AccentBaseColor); rd.Add("AccentColor", AccentColor); rd.Add("AccentColor2", AccentColor2); rd.Add("AccentColor3", AccentColor3); rd.Add("AccentColor4", AccentColor4); rd.Add("HighlightBrush", HighlightBrush); rd.Add("AccentBaseColorBrush", AccentBaseColorBrush); rd.Add("AccentColorBrush", AccentColorBrush); rd.Add("AccentColorBrush2", AccentColorBrush2); rd.Add("AccentColorBrush3", AccentColorBrush3); rd.Add("AccentColorBrush4", AccentColorBrush4); rd.Add("WindowTitleColorBrush", AccentColorBrush); rd.Add("AccentSelectedColorBrush", Brushes.White); rd.Add("IdealForegroundColor", Colors.White); rd.Add("IdealForegroundColorBrush", Brushes.White); rd.Add("CheckmarkFill", AccentColorBrush); rd.Add("RightArrowFill", AccentColorBrush); return(rd); }
/// <summary> /// Attempt to switch to the theme stated in <paramref name="nextThemeToSwitchTo"/>. /// The given name must map into the <seealso cref="Edi.Themes.ThemesVM.EnTheme"/> enumeration. /// </summary> /// <param name="nextThemeToSwitchTo"></param> private void SwitchToSelectedTheme(IThemeBase nextThemeToSwitchTo) { const string themesModul = "Edi.Themes.dll"; try { // set the style of the message box display in back-end system. _MsgBox.Style = MsgBoxStyle.System; // Get WPF Theme definition from Themes Assembly IThemeBase theme = ApplicationThemes.SelectedTheme; if (theme != null) { Application.Current.Resources.MergedDictionaries.Clear(); string themesPathFileName = Assembly.GetEntryAssembly().Location; themesPathFileName = System.IO.Path.GetDirectoryName(themesPathFileName); themesPathFileName = System.IO.Path.Combine(themesPathFileName, themesModul); Assembly.LoadFrom(themesPathFileName); if (System.IO.File.Exists(themesPathFileName) == false) { _MsgBox.Show(string.Format(CultureInfo.CurrentCulture, Util.Local.Strings.STR_THEMING_MSG_CANNOT_FIND_PATH, themesModul), Util.Local.Strings.STR_THEMING_CAPTION, MsgBoxButtons.OK, MsgBoxImage.Error); return; } foreach (var item in theme.Resources) { try { var res = new Uri(item, UriKind.Relative); if (Application.LoadComponent(res) is ResourceDictionary) { ResourceDictionary dictionary = Application.LoadComponent(res) as ResourceDictionary; Application.Current.Resources.MergedDictionaries.Add(dictionary); } } catch (Exception exp) { _MsgBox.Show(exp, string.Format(CultureInfo.CurrentCulture, "'{0}'", item), MsgBoxButtons.OK, MsgBoxImage.Error); } } } } catch (Exception exp) { _MsgBox.Show(exp, Util.Local.Strings.STR_THEMING_CAPTION, MsgBoxButtons.OK, MsgBoxImage.Error); } finally { // set the style of the message box display in back-end system. if (nextThemeToSwitchTo.WPFThemeName != "Generic") { _MsgBox.Style = MsgBoxStyle.WPFThemed; } } }
public static void MenuServiceInit() { Uri uri = new Uri("\\Services\\MenuService\\ContextMenu.xaml", UriKind.RelativeOrAbsolute); contextMenuResource = Application.LoadComponent(uri) as ResourceDictionary; }
/// <summary> /// 设置颜色 /// </summary> /// <param name="colorName"></param> /// <param name="c"></param> public static void SetColor(ResourceDictionary resource, string colorName, Color c) { resource.Remove(colorName); resource.Add(colorName, new SolidColorBrush(c)); }
private static bool RemoveResourceDictionaryFromResourcesDeep(ResourceDictionary resourceDictionaryToRemove, ResourceDictionary rootResourceDictionary) { if (!rootResourceDictionary.MergedDictionaries.Any()) { return(false); } if (rootResourceDictionary.MergedDictionaries.Contains(resourceDictionaryToRemove)) { rootResourceDictionary.MergedDictionaries.Remove(resourceDictionaryToRemove); return(true); } return(rootResourceDictionary.MergedDictionaries.Any(dict => RemoveResourceDictionaryFromResourcesDeep(resourceDictionaryToRemove, dict))); }
private void ChangeTheme() { string ThemeName = SettingHelper.Theme; ResourceDictionary newDictionary = new ResourceDictionary(); switch (ThemeName) { case "Dark": RequestedTheme = ElementTheme.Dark; break; case "Red": newDictionary.Source = new Uri("ms-appx:///Theme/RedTheme.xaml", UriKind.RelativeOrAbsolute); Application.Current.Resources.MergedDictionaries.Clear(); Application.Current.Resources.MergedDictionaries.Add(newDictionary); RequestedTheme = ElementTheme.Dark; RequestedTheme = ElementTheme.Light; break; case "Blue": newDictionary.Source = new Uri("ms-appx:///Theme/BlueTheme.xaml", UriKind.RelativeOrAbsolute); Application.Current.Resources.MergedDictionaries.Clear(); Application.Current.Resources.MergedDictionaries.Add(newDictionary); RequestedTheme = ElementTheme.Dark; RequestedTheme = ElementTheme.Light; break; case "Green": newDictionary.Source = new Uri("ms-appx:///Theme/GreenTheme.xaml", UriKind.RelativeOrAbsolute); Application.Current.Resources.MergedDictionaries.Clear(); Application.Current.Resources.MergedDictionaries.Add(newDictionary); RequestedTheme = ElementTheme.Dark; RequestedTheme = ElementTheme.Light; break; case "Pink": newDictionary.Source = new Uri("ms-appx:///Theme/PinkTheme.xaml", UriKind.RelativeOrAbsolute); Application.Current.Resources.MergedDictionaries.Clear(); Application.Current.Resources.MergedDictionaries.Add(newDictionary); RequestedTheme = ElementTheme.Dark; RequestedTheme = ElementTheme.Light; break; case "Purple": newDictionary.Source = new Uri("ms-appx:///Theme/PurpleTheme.xaml", UriKind.RelativeOrAbsolute); Application.Current.Resources.MergedDictionaries.Clear(); Application.Current.Resources.MergedDictionaries.Add(newDictionary); RequestedTheme = ElementTheme.Dark; RequestedTheme = ElementTheme.Light; break; case "Yellow": newDictionary.Source = new Uri("ms-appx:///Theme/YellowTheme.xaml", UriKind.RelativeOrAbsolute); Application.Current.Resources.MergedDictionaries.Clear(); Application.Current.Resources.MergedDictionaries.Add(newDictionary); RequestedTheme = ElementTheme.Dark; RequestedTheme = ElementTheme.Light; break; case "EMT": newDictionary.Source = new Uri("ms-appx:///Theme/EMTTheme.xaml", UriKind.RelativeOrAbsolute); Application.Current.Resources.MergedDictionaries.Clear(); Application.Current.Resources.MergedDictionaries.Add(newDictionary); // img_Hello.Source = new BitmapImage(new Uri("ms-appx:///Assets/Logo/EMT.png")); RequestedTheme = ElementTheme.Dark; RequestedTheme = ElementTheme.Light; break; } //tuic.To = this.ActualWidth; //storyboardPopOut.Begin(); ChangeTitbarColor(); }
protected override void OnStartup(StartupEventArgs e) { var assembly = Assembly.GetExecutingAssembly(); var cwd = AppDomain.CurrentDomain.GetData("path") as string ?? Path.GetDirectoryName(assembly.Location); Directory.SetCurrentDirectory(cwd); base.OnStartup(e); var appVersion = assembly.GetName().Version; var preferences = SettingsService.Preferences; if (preferences.Version != appVersion.ToString()) { preferences.Version = appVersion.ToString(); if (File.Exists("stacktrace.log")) { File.Delete("stacktrace.log"); } } var args = Environment.GetCommandLineArgs(); preferences.IsAdvanced = args.Any(x => x.Equals("advanced", StringComparison.OrdinalIgnoreCase)); preferences.IsPortable = args.Any(x => x.Equals("portable", StringComparison.OrdinalIgnoreCase)); preferences.BasePath = cwd; SettingsService.Preferences = preferences; foreach (var file in requiredFiles.Where(file => !File.Exists(file))) { Exceptions.ShowErrorBox( $"slimCat will now exit. \nReason: Required theme file \"{file}\" is missing. This is likely due to a bad theme install.\n" + "Please install themes by extracting a theme over the default theme, overwriting when prompted to.", "slimCat Fatal Error"); Environment.Exit(-1); } /* * Here we load in the theme. * You may notice that this is somewhat involved for just loading in some files, but there are two reasons for this: * * 1) slimCat can be ran with the loader in such a way that the starting assembly location is different from running * locally. This complicates loading in statically, to say the least. * * 2) We might want to load a different theme based on settings. This is not a feature yet, but we load settings literally * just a few lines ago, so it is a certain possibility. * * Some other notes here: colors needs to be loaded in first due to themes.xaml using it. I've tried NOT using siteoforigin * in the pack and it did not work well at all, since it required the theme file to be built into the assembly (defeating the point). */ Action <string> addResourceDictionary = partialUri => { var dict = new ResourceDictionary { Source = new Uri("pack://siteoforigin:,,,/" + partialUri) }; Current.Resources.MergedDictionaries.Add(dict); }; try { // we will attempt to add them by first looking for a /theme near our executing assembly addResourceDictionary("Theme/Colors.xaml"); addResourceDictionary("Theme/Theme.xaml"); } catch (IOException ex) when(ex is FileNotFoundException || ex is DirectoryNotFoundException) { // if that doesn't work, look for theme in client/theme addResourceDictionary("Client/Theme/Colors.xaml"); addResourceDictionary("Client/Theme/Theme.xaml"); } // this depends on our external themes, so it has to be loaded last var embeddedTheme = new ResourceDictionary { Source = new Uri("Theme/EmbeddedTheme.xaml", UriKind.Relative) }; Current.Resources.MergedDictionaries.Add(embeddedTheme); new Bootstrapper().Run(); }
public DictionaryTheme(ResourceDictionary themeResourceDictionary) { this.ThemeResourceDictionary = themeResourceDictionary; }
/// <summary> /// 构造函数 /// </summary> public Assets() { (this.language = new ResourceDictionary()).Source = DEFAULT_LANGUAGE; }
public void ResourceDictionaryCtor() { var rd = new ResourceDictionary(); Assert.AreEqual(0, rd.Count()); }
static MultiChoiceKeyConverter() { dict = new ResourceDictionary(); dict.Source = new Uri("pack://application:,,,/Controls;component/Views/Buttons/MultiChoiceButton.xaml"); }
static string GetName(ResourceDictionary dic) { return(Converter.Convert(StringHelper.Split(dic.Source.ToString(), ";component/").Last())); }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (parameter != null) { object _result = null; string _propertyName = parameter.ToString(); _result = StyleHelper.FindStyleValue(value, _propertyName, DsxDataGrid.FooterStyleProperty, DsxColumn.FooterStyleProperty); if (_result != null) { return(_result); } // defaults if (sStyleResources == null) { sStyleResources = new ResourceDictionary(); sStyleResources.Source = new Uri("/DsxGridCtrl;component/Themes/Styles.xaml", UriKind.Relative); } Style _footerStyle = sStyleResources["dsxFooterStyleGray"] as Style; if (_footerStyle == null) { throw new Exception("if 'dsxFooterStyleGray' is not present in Styles.xaml, a FooterStyle must be set at design time"); } if (_propertyName.Equals(Control.BackgroundProperty.Name)) { return(_footerStyle.GetStylePropertyValue <Brush> ("Background", Brushes.WhiteSmoke)); } else if (_propertyName.Equals(Control.ForegroundProperty.Name)) { return(_footerStyle.GetStylePropertyValue <Brush> ("Foreground", SystemColors.ControlTextBrush)); } else if (_propertyName.Equals(Border.BorderBrushProperty.Name)) { return(_footerStyle.GetStylePropertyValue <Brush> ("BorderBrush", Brushes.DarkGray)); } else if (_propertyName.Equals(FrameworkElement.HorizontalAlignmentProperty.Name)) { return(_footerStyle.GetStylePropertyValue <HorizontalAlignment> ("HorizontalAlignment", HorizontalAlignment.Left)); } else if (_propertyName.Equals(FrameworkElement.VerticalAlignmentProperty.Name)) { return(_footerStyle.GetStylePropertyValue <VerticalAlignment> ("VerticalAlignment", VerticalAlignment.Center)); } else if (_propertyName.Equals(Border.CornerRadiusProperty.Name)) { return(_footerStyle.GetStylePropertyValue <CornerRadius> ("CornerRadius", new CornerRadius(0, 0, 0, 0))); } else if (_propertyName.Equals(Border.BorderThicknessProperty.Name)) { return(_footerStyle.GetStylePropertyValue <Thickness> ("BorderThickness", new Thickness(0, 1, 0, 1))); } else if (_propertyName.Equals(Control.PaddingProperty.Name)) { return(_footerStyle.GetStylePropertyValue <Thickness> ("Padding", new Thickness(6, 0, 6, 0))); } else if (_propertyName.Equals(FrameworkElement.MarginProperty.Name)) { return(_footerStyle.GetStylePropertyValue <Thickness> ("Margin", new Thickness(0, 0, 0, 0))); } } return(null); }
private static void ApplyCustom(ResourceDictionary appResource, string stylePath) { ApplyCustom(appResource, new Uri(stylePath)); }
public static void CreateAppStyleBy(Color color, bool changeImmediately = false) { // create a runtime accent resource dictionary var resourceDictionary = new ResourceDictionary(); resourceDictionary.Add("HighlightColor", color); resourceDictionary.Add("AccentBaseColor", color); resourceDictionary.Add("AccentColor", Color.FromArgb((byte)(204), color.R, color.G, color.B)); resourceDictionary.Add("AccentColor2", Color.FromArgb((byte)(153), color.R, color.G, color.B)); resourceDictionary.Add("AccentColor3", Color.FromArgb((byte)(102), color.R, color.G, color.B)); resourceDictionary.Add("AccentColor4", Color.FromArgb((byte)(51), color.R, color.G, color.B)); resourceDictionary.Add("HighlightBrush", GetSolidColorBrush((Color)resourceDictionary["HighlightColor"])); resourceDictionary.Add("AccentBaseColorBrush", GetSolidColorBrush((Color)resourceDictionary["AccentBaseColor"])); resourceDictionary.Add("AccentColorBrush", GetSolidColorBrush((Color)resourceDictionary["AccentColor"])); resourceDictionary.Add("AccentColorBrush2", GetSolidColorBrush((Color)resourceDictionary["AccentColor2"])); resourceDictionary.Add("AccentColorBrush3", GetSolidColorBrush((Color)resourceDictionary["AccentColor3"])); resourceDictionary.Add("AccentColorBrush4", GetSolidColorBrush((Color)resourceDictionary["AccentColor4"])); resourceDictionary.Add("WindowTitleColorBrush", GetSolidColorBrush((Color)resourceDictionary["AccentColor"])); resourceDictionary.Add("ProgressBrush", new LinearGradientBrush( new GradientStopCollection(new[] { new GradientStop((Color)resourceDictionary["HighlightColor"], 0), new GradientStop((Color)resourceDictionary["AccentColor3"], 1) }), // StartPoint="1.002,0.5" EndPoint="0.001,0.5" startPoint: new Point(1.002, 0.5), endPoint: new Point(0.001, 0.5))); resourceDictionary.Add("CheckmarkFill", GetSolidColorBrush((Color)resourceDictionary["AccentColor"])); resourceDictionary.Add("RightArrowFill", GetSolidColorBrush((Color)resourceDictionary["AccentColor"])); resourceDictionary.Add("IdealForegroundColor", IdealTextColor(color)); resourceDictionary.Add("IdealForegroundColorBrush", GetSolidColorBrush((Color)resourceDictionary["IdealForegroundColor"])); resourceDictionary.Add("IdealForegroundDisabledBrush", GetSolidColorBrush((Color)resourceDictionary["IdealForegroundColor"], 0.4)); resourceDictionary.Add("AccentSelectedColorBrush", GetSolidColorBrush((Color)resourceDictionary["IdealForegroundColor"])); resourceDictionary.Add("MetroDataGrid.HighlightBrush", GetSolidColorBrush((Color)resourceDictionary["AccentColor"])); resourceDictionary.Add("MetroDataGrid.HighlightTextBrush", GetSolidColorBrush((Color)resourceDictionary["IdealForegroundColor"])); resourceDictionary.Add("MetroDataGrid.MouseOverHighlightBrush", GetSolidColorBrush((Color)resourceDictionary["AccentColor3"])); resourceDictionary.Add("MetroDataGrid.FocusBorderBrush", GetSolidColorBrush((Color)resourceDictionary["AccentColor"])); resourceDictionary.Add("MetroDataGrid.InactiveSelectionHighlightBrush", GetSolidColorBrush((Color)resourceDictionary["AccentColor2"])); resourceDictionary.Add("MetroDataGrid.InactiveSelectionHighlightTextBrush", GetSolidColorBrush((Color)resourceDictionary["IdealForegroundColor"])); resourceDictionary.Add("MahApps.Metro.Brushes.ToggleSwitchButton.OnSwitchBrush.Win10", GetSolidColorBrush((Color)resourceDictionary["AccentColor"])); resourceDictionary.Add("MahApps.Metro.Brushes.ToggleSwitchButton.OnSwitchMouseOverBrush.Win10", GetSolidColorBrush((Color)resourceDictionary["AccentColor2"])); resourceDictionary.Add("MahApps.Metro.Brushes.ToggleSwitchButton.ThumbIndicatorCheckedBrush.Win10", GetSolidColorBrush((Color)resourceDictionary["IdealForegroundColor"])); // applying theme to MahApps var resDictName = string.Format("ApplicationAccent_{0}.xaml", color.ToString().Replace("#", string.Empty)); var fileName = Path.Combine(Path.GetTempPath(), resDictName); using (var writer = System.Xml.XmlWriter.Create(fileName, new System.Xml.XmlWriterSettings { Indent = true })) { System.Windows.Markup.XamlWriter.Save(resourceDictionary, writer); writer.Close(); } resourceDictionary = new ResourceDictionary() { Source = new Uri(fileName, UriKind.Absolute) }; var newAccent = new Accent { Name = resDictName, Resources = resourceDictionary }; ThemeManager.AddAccent(newAccent.Name, newAccent.Resources.Source); if (changeImmediately) { var application = Application.Current; //var applicationTheme = ThemeManager.AppThemes.First(x => string.Equals(x.Name, "BaseLight")); // detect current application theme Tuple <AppTheme, Accent> applicationTheme = ThemeManager.DetectAppStyle(application); ThemeManager.ChangeAppStyle(application, newAccent, applicationTheme.Item1); } }
public static void ApplyCustom(ResourceDictionary appResource, string assemblyName, string relativeXamlPath) { ApplyCustom(appResource, GResourceUtility.GetUri(assemblyName, relativeXamlPath)); }
public void UpdateResourceDict(ResourceDictionary dictionary) { Resources.MergedDictionaries.Clear(); Resources.MergedDictionaries.Add(dictionary); }
private void SettingsWindow_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { if (((bool)e.OldValue == false) && ((bool)e.NewValue == true)) { LockBarCheckBox.IsChecked = Config.IsLocked; AutoHideCheckBox.IsChecked = Config.AutoHide; SmallButtonsCheckBox.IsChecked = Config.UseSmallIcons; AllowPeekCheckBox.IsChecked = Config.AllowPeekDesktop; if (Config.DockMode == AppBarWindow.AppBarDockMode.Left) { SetToggleButtons(BarPositionButtonsGrid, 1); //BarPositionComboBox.SelectedIndex = 1; } else if (Config.DockMode == AppBarWindow.AppBarDockMode.Right) { SetToggleButtons(BarPositionButtonsGrid, 2); //BarPositionComboBox.SelectedIndex = 2; } else if (Config.DockMode == AppBarWindow.AppBarDockMode.Top) { SetToggleButtons(BarPositionButtonsGrid, 3); //BarPositionComboBox.SelectedIndex = 3; } else { SetToggleButtons(BarPositionButtonsGrid, 0); //BarPositionComboBox.SelectedIndex = 0; } if (Config.TaskbarCombineMode == Config.CombineMode.WhenFull) { SetToggleButtons(TaskbarCombineModeGrid, 2); //TaskbarCombineModeComboBox.SelectedIndex = 2; } else if (Config.TaskbarCombineMode == Config.CombineMode.Never) { SetToggleButtons(TaskbarCombineModeGrid, 3); //TaskbarCombineModeComboBox.SelectedIndex = 3; } else { if (Config.ShowCombinedLabels) { SetToggleButtons(TaskbarCombineModeGrid, 0); //TaskbarCombineModeComboBox.SelectedIndex = 0; } else { SetToggleButtons(TaskbarCombineModeGrid, 1); //TaskbarCombineModeComboBox.SelectedIndex = 1; } } if (Config.TrayClockDateMode == Config.ClockDateMode.AlwaysShow) { SetToggleButtons(TaskbarClockDateModeGrid, 0); //TaskbarClockDateModeComboBox.SelectedIndex = 0; } else if (Config.TrayClockDateMode == Config.ClockDateMode.NeverShow) { SetToggleButtons(TaskbarClockDateModeGrid, 2); //TaskbarClockDateModeComboBox.SelectedIndex = 2; } else { SetToggleButtons(TaskbarClockDateModeGrid, 1); //TaskbarClockDateModeComboBox.SelectedIndex = 1; } ShowKillProcessesEntryToggleSwitch.IsChecked = Config.ShowKillProcessesInJumpLists; CurrentSkinComboBox.Items.Clear(); CurrentSkinComboBox.Items.Add("Shale"); //foreach (string s in Directory.EnumerateFiles(Environment.ExpandEnvironmentVariables(@"%appdata%\Start9\TempData\Everythingbar_Skins"))) foreach (string s in Directory.EnumerateDirectories(Environment.ExpandEnvironmentVariables(@"%appdata%\Start9\TempData\Everythingbar_Skins"))) { string expectedSkinPath = System.IO.Path.Combine(s, "Skin.dll"); if (File.Exists(expectedSkinPath)) //System.IO.Path.GetExtension(s).ToLowerInvariant().EndsWith("dll")) { var assembly = System.Reflection.Assembly.LoadFile(expectedSkinPath); //This is probably a terrible idea idk, todo: checc with flec var dictionary = new ResourceDictionary() { Source = new Uri(@"/Skin;component/Themes/Skin.xaml", UriKind.RelativeOrAbsolute) }; CurrentSkinComboBox.Items.Add(new ComboBoxItem() { Content = System.IO.Path.GetFileName(s), Tag = dictionary }); } } } }
/// <summary> /// Processes the generators. /// </summary> /// <param name="parentClass">The parent class.</param> /// <param name="method">The method.</param> /// <param name="value">The value.</param> /// <param name="baseName">Name of the base.</param> /// <param name="dictionary">The dictionary.</param> /// <returns></returns> public CodeExpression ProcessGenerators(CodeTypeDeclaration parentClass, CodeMemberMethod method, object value, string baseName, ResourceDictionary dictionary = null) { if (value == null) { return(new CodePrimitiveExpression(null)); } IGeneratorValue generator; Type valueType = value.GetType(); CodeExpression valueExpression = null; if (Generators.TryGetValue(valueType, out generator)) { valueExpression = generator.Generate(parentClass, method, value, baseName, dictionary); } else if (valueType.IsEnum) { CodeTypeReferenceExpression typeReference = new CodeTypeReferenceExpression(valueType.Name); valueExpression = new CodeFieldReferenceExpression(typeReference, value.ToString()); } else { valueExpression = new CodePrimitiveExpression("NOT SUPPORTED!"); string errorText = string.Format("Type {0} not supported", valueType.Name); Console.WriteLine(errorText); CodeSnippetStatement error = new CodeSnippetStatement("#error " + errorText); method.Statements.Add(error); } return(valueExpression); }
private void ApplyButton_Click(object sender, RoutedEventArgs e) { Config.IsLocked = LockBarCheckBox.IsChecked.Value; Config.AutoHide = AutoHideCheckBox.IsChecked.Value; Config.UseSmallIcons = SmallButtonsCheckBox.IsChecked.Value; Config.AllowPeekDesktop = AllowPeekCheckBox.IsChecked.Value; Config.ShowKillProcessesInJumpLists = ShowKillProcessesEntryToggleSwitch.IsChecked.Value; if (GetSelectedToggleButton(BarPositionButtonsGrid) == 1) //BarPositionComboBox.SelectedIndex == 1) { Config.DockMode = AppBarWindow.AppBarDockMode.Left; } else if (GetSelectedToggleButton(BarPositionButtonsGrid) == 2) //BarPositionComboBox.SelectedIndex == 2) { Config.DockMode = AppBarWindow.AppBarDockMode.Right; } else if (GetSelectedToggleButton(BarPositionButtonsGrid) == 3) //BarPositionComboBox.SelectedIndex == 3) { Config.DockMode = AppBarWindow.AppBarDockMode.Top; } else { Config.DockMode = AppBarWindow.AppBarDockMode.Bottom; } if (GetSelectedToggleButton(TaskbarCombineModeGrid) == 2) //TaskbarCombineModeComboBox.SelectedIndex == 2) { Config.TaskbarCombineMode = Config.CombineMode.WhenFull; } else if (GetSelectedToggleButton(TaskbarCombineModeGrid) == 3) //TaskbarCombineModeComboBox.SelectedIndex == 3) { Config.TaskbarCombineMode = Config.CombineMode.Never; } else { Config.TaskbarCombineMode = Config.CombineMode.Always; if (GetSelectedToggleButton(TaskbarCombineModeGrid) == 1) //TaskbarCombineModeComboBox.SelectedIndex == 1) { Config.ShowCombinedLabels = false; } else { Config.ShowCombinedLabels = true; } } if (GetSelectedToggleButton(TaskbarClockDateModeGrid) == 1) //TaskbarClockDateModeComboBox.SelectedIndex == 1) { Config.TrayClockDateMode = Config.ClockDateMode.Auto; } else if (GetSelectedToggleButton(TaskbarClockDateModeGrid) == 2) //TaskbarClockDateModeComboBox.SelectedIndex == 2) { Config.TrayClockDateMode = Config.ClockDateMode.NeverShow; } else { Config.TrayClockDateMode = Config.ClockDateMode.AlwaysShow; } if (CurrentSkinComboBox.SelectedItem == "Shale") { //if (Application.Current.Resources.MergedDictionaries.Count > 1) Application.Current.Resources.MergedDictionaries.Remove(_dictionary); } else if (CurrentSkinComboBox.SelectedItem != null) { Application.Current.Resources.MergedDictionaries.Add((CurrentSkinComboBox.SelectedItem as ComboBoxItem).Tag as ResourceDictionary); _dictionary = (CurrentSkinComboBox.SelectedItem as ComboBoxItem).Tag as ResourceDictionary; } Config.InvokeConfigUpdated(this, new EventArgs()); if (sender == OkButton) { Close(); } }
public static void AddXamlResource(this ResourceDictionary dictionary, string xamlFileName, Assembly xamlFileAssembly) { dictionary.AddXamlResource(xamlFileName, xamlFileAssembly.GetName().Name); }
public static void RegistResource(ResourceDictionary resource) { Resources.Add(resource); }
/// <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; }
/// <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. /// <para/> /// This method will use the passed resources. /// </summary> /// <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="defaultPrefix">The default prefix, uses to determine the styles as base for other styles.</param> /// <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 sourceResources, ResourceDictionary targetResources, string defaultPrefix = DefaultKeyPrefix) { CreateStyleForwardersForDefaultStyles(sourceResources, sourceResources, targetResources, false, defaultPrefix); }
/// <summary> /// Recreates the default styles based on theme. /// </summary> /// <param name="rootResourceDictionary">The root resource dictionary.</param> /// <param name="resources">The resources to fix.</param> /// <param name="defaultPrefix">The default prefix.</param> /// <remarks> /// This method is introduced due to the lack of the ability to use DynamicResource for the BasedOn property when /// defining styles inside a derived theme. /// </remarks> /// <exception cref="ArgumentNullException">The <paramref name="rootResourceDictionary"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="resources"/> is <c>null</c>.</exception> /// <exception cref="ArgumentException">The <paramref name="defaultPrefix"/> is <c>null</c> or whitespace.</exception> private static void RecreateDefaultStylesBasedOnTheme(ResourceDictionary rootResourceDictionary, ResourceDictionary resources, string defaultPrefix) { Argument.IsNotNull("rootResourceDictionary", rootResourceDictionary); Argument.IsNotNull("resources", resources); Argument.IsNotNull("defaultPrefix", defaultPrefix); var keys = (from key in resources.Keys as ICollection <object> where key is string && ((string)key).StartsWith(defaultPrefix, StringComparison.InvariantCulture) && ((string)key).EndsWith(DefaultKeyPostfix, StringComparison.InvariantCulture) select key).ToList(); foreach (string key in keys) { var style = resources[key] as Style; if (style == null) { continue; } var basedOnType = FindFrameworkElementStyleIsBasedOn(resources.Source, key); if (basedOnType == null) { continue; } resources[key] = CloneStyleIfBasedOnControl(rootResourceDictionary, style, basedOnType); } foreach (var resourceDictionary in resources.MergedDictionaries) { RecreateDefaultStylesBasedOnTheme(rootResourceDictionary, resourceDictionary, defaultPrefix); } }
protected void AddLanguageResource(LanguageType type, ResourceDictionary source) { Culture.Add(type, source); }