dath
dath

Reputation: 915

C# UWP data binding in TextBox Resources

I have implemented a light/dark theme in my app where the user can either press the light or dark button and all the app colours will change. I do this by binding a SolidColorBrush to the background and foreground of each element e.g.

In viewmodel:

private SolidColorBrush fontColour;
        public SolidColorBrush FontColour
        {
            get { return fontColour; }
            set
            {
                fontColour = value;
                OnPropertyChanged(nameof(FontColour));
            }
        }

In xaml:

<TextBox Text="{Binding EventLog}"
                             Foreground="{Binding FontColour}"
                             Background="{Binding ColourTheme5}"/>

This works as expected. However, when I try to do the same thing within TextBox.Resources, the binding does not work at all e.g.

(binding for TextControlForegroundPointerOver does not work)

<TextBox Text="{Binding EventLog}"
                             Foreground="{Binding FontColour}"
                             Background="{Binding ColourTheme5}">

                        <TextBox.Resources>

                            <SolidColorBrush x:Key="TextControlForegroundPointerOver"
                                             Color="{Binding FontColour}"
                                             Opacity="1" />
                        </TextBox.Resources>
                    </TextBox>

Upvotes: 2

Views: 360

Answers (2)

Oleg Mikhailov
Oleg Mikhailov

Reputation: 252

You are reinventing the wheel. Xaml has Theme Resources and RequestedTheme property that can be set at page level.

Upvotes: 0

phimath
phimath

Reputation: 151

I am almost certain, that TextBox.Resources is not a DependencyProperty, thus, cannot be bound.

If you want to set it at compile time, use the code initialization (just like the example you put at the very bottom).

If you want to set it at run time, you have to do it programmatically in the constructor if the window/user control, where you have put your TextBox. This should work.

Edit: I missed the "light/dark theme" part of the question, thus I want to add:

There is a great part regarding Themes in the Windows Community Toolkit, further documentation and also a part in their sample app you can find at https://learn.microsoft.com/en-us/windows/communitytoolkit/helpers/themelistener.

Upvotes: 2

Related Questions