locked
[UWP] How to set ThemeResource in C# RRS feed

  • Question

  • Hi! I make UWP app and I want to set ThemeResource in C#:

    MessageBubbleThemes.xaml

    <ResourceDictionary
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <ResourceDictionary.ThemeDictionaries>
            <ResourceDictionary x:Key="Light">
                <SolidColorBrush x:Key="MessageBubbleBackground" Color="#bdc3c7"/>
                <SolidColorBrush x:Key="MessageBubbleForeground" Color="Black"/>
                <SolidColorBrush x:Key="MyMessageBubbleBackground" Color="#3498db"/>
                <SolidColorBrush x:Key="MyMessageBubbleForeground" Color="White"/>
            </ResourceDictionary>
            <ResourceDictionary x:Key="Dark">
                <SolidColorBrush x:Key="MessageBubbleBackground" Color="#34495e"/>
                <SolidColorBrush x:Key="MessageBubbleForeground" Color="White"/>
                <SolidColorBrush x:Key="MyMessageBubbleBackground" Color="#27ae60"/>
                <SolidColorBrush x:Key="MyMessageBubbleForeground" Color="White"/>
            </ResourceDictionary>
        </ResourceDictionary.ThemeDictionaries>
    </ResourceDictionary>


    MessageBubble.xaml

    <Grid x:Name="bubbleBody" Background="{ThemeResource MessageBubbleBackground}">
        <RichTextBlock Margin="10" MaxWidth="300">
            <Paragraph>
               <Run x:Name="bubbleText"/>
            </Paragraph>
        </RichTextBlock>
    </Grid>

    MessageBubble.xaml.cs

    private static ResourceDictionary _bubblesThemes = new ResourceDictionary()
    {
        Source = new System.Uri("ms-appx:///MessageBubbleThemes.xaml")
    };
    
    .......
    
    bubbleBody.Background = (SolidColorBrush)_bubblesThemes["MyMessageBubbleBackground"];
    bubbleText.Foreground = (SolidColorBrush)_bubblesThemes["MyMessageBubbleForeground"];

    If I set Background as ThemeResource in XAML, then MessageBubble change his background on theme changed in Settings app, but if I set Background in C#, then MessageBubble don't change his background on theme changed.

    How can I solve it?

    Saturday, August 1, 2020 7:56 AM

All replies

  • Hi Puelt,

    Since this thread is related to UWP, so I suggest that you can ask this question in Microsoft Q&A.

    The Visual C# forum discusses and asks questions about the C# programming language, IDE, libraries, samples, and tools.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, August 3, 2020 2:52 AM