问题
Is it possible to dynamically load a different style ResourceDictionary at run time depending on a certain condition?
I want to have a single build of my app but have different colours/branding depending on a specific setting. Assuming the above isn't possible would I best achieve this?
回答1:
ResourceDictionary cannot be set dynamically at runtime as far as I remember - not on UWP. IMHO the only way is to change ColorBrushes or the whole styles.
First option: If you need to change colors dynamically, then you need to create Brush within ResourceDictionary
<SolidColorBrush x:Key="MyBrush">#333344</SolidColorBrush>
and use it with your styles/xaml layouts and so on.
To change it you would need to (assuming you have only one resource distionary set or the one containing color brushes is first) take the brush from the dictionary and replace its color.
if (Application.Current.Resources.MergedDictionaries[0].ContainsKey("MyBrush"))
{
var brush = Application.Current.Resources.MergedDictionaries[0]["MyBrush"] as SolidColorBrush;
if (brush != null)
{
brush.Color = return new Color() { A = 255, R = r, G = g, B = b };
}
}
Second option: If you need to change the whole style at runtime (assuming you have MyStyle and MyOtherStyle set within resource dictionaries, and want to apply it to some control named MyControl):
switch(anyValue)
{
case 1:
var myStyle = Application.Current.Resources["MyStyle"] as Style;
if(myStyle != null)
{
MyControl.Style = myStyle;
}
break;
case 2:
var myOtherStyle = Application.Current.Resources["MyOtherStyle"] as Style;
if(myOtherStyle != null)
{
MyControl.Style = myOtherStyle;
}
break;
}
Third option: change the style with the VisualStates set for the control. It would need to write your own VisualStates for the controls you want to change and then switching beetwen them manually. Never tried it so I don't know how reliable this way could be. It looks like the best way in case of performance (assumption only) but keeping the VisualStates by hand for every control may need to implement your own VisualStateManager and may cause trouble with keeping the right VisualState at the time you want it.
来源:https://stackoverflow.com/questions/43251462/uwp-dynamically-load-different-styles-xaml