Set static resource in code

前端 未结 3 464
粉色の甜心
粉色の甜心 2021-02-05 07:20

I have a few styles in my App.xaml file:




        
相关标签:
3条回答
  • 2021-02-05 07:28

    A StaticResource is static. You can't change them once the application has compiled.

    For this purpose, there is DynamicResource:

    A DynamicResource will create a temporary expression during the initial compilation and thus defer lookup for resources until the requested resource value is actually required in order to construct an object.

    Also note that you can find the reference to the other resource better using FindResource. Try something like this (full working sample):

    In MainPage.xaml:

    <Window.Resources>
        <Color R="255" x:Key="styleRed" />
        <Style x:Key="abc" TargetType="StackPanel">
            <Setter Property="Background" Value="Blue" />
        </Style>
    </Window.Resources>
    

    In MainPage.xaml.cs:

    Style style = this.FindResource("abc") as Style;
    var r = this.FindResource("styleRed");
    
    foreach (Setter s in style.Setters)
    {
        if (s.Property == StackPanel.BackgroundProperty)
        {
            s.Value = r;
        }
    }
    
    0 讨论(0)
  • 2021-02-05 07:35

    Why are you modifying the Style instead of setting the Background-Property of your targeted StackPanel directly? Since a 'Local value' has a higher precedence than 'Style setters' the value that you write into Background from code behind would be used

    Means:

    (1) Give a name to your stackpanel x:Name="spBla"

    (2) Assign the Brush to the Background of spBla ( something like spBla.Background=Application.Current.Resources["styleRed"] as SolidColorBrush; )

    You can learn more about value precedence here:

    http://msdn.microsoft.com/en-us/library/ms743230(v=vs.110).aspx

    0 讨论(0)
  • 2021-02-05 07:51

    If I understand correctly, you are wanting to set up a style that allows you to only change specific stackpanels, so you don't have to set them all. Give this suggestion a try (note: it is a suggestion and I have not tested it, but hopefully it is in the right direction)

    <SolidColorBrush x:Key="styleBlue" Color="#FF4B77BE"/>
    <SolidColorBrush x:Key="styleRed" Color="#FFF64747"/>
    <SolidColorBrush x:Key="styleOrange" Color="#FFF89406"/>
    <SolidColorBrush x:Key="styleGreen" Color="#FF1BBC9B"/>
    <SolidColorBrush x:Key="styleYellow" Color="#FFF9BF3B"/>
    
    <Style x:Key="stackpanelBackground" TargetType="StackPanel">
        <Setter Property="Background" Value="{Binding Background, FallbackValue={StaticResource styleBlue}}"/>
    </Style>
    

    Or try TemplateBinding instead of Binding, like I said it is a suggestion and I haven't tested it. This would give you a binding for the background, and a fallback value for a stackpanel that you haven't set a background color for. Let me know how or if this works for you :)

    0 讨论(0)
提交回复
热议问题