Changing Window background color dynamically

Feb 10, 2010 at 2:21 AM
Edited Feb 10, 2010 at 2:22 AM

Hi there,

I have been using the Window library for an application which requires that the color of the window background be configurable by the user. Is there a way to expose the background rectangle to code behind so that I can programmatically set the fill color?

I believe the relevant code is in the Window.xaml, the last Rectangle element after the "Background" comment.

Sorry if this is a bit of a noob question since I've only just started XAML and only know the basics.

Cheers!

Coordinator
Feb 10, 2010 at 11:02 AM

lueyyou,

You need to learn a little bit more about xaml, so you need to learn about how Styles and Templates works, and so its easy to change the background. You can also change completely the appearance of the window.

Inside the window style, you can set up the background throught the TemplateBinding bind in the element that you choose to show the background, for example:

Inside the window style:               <ElementChoosed Background="{TemplateBinding Background}" ...

Vítor

Feb 11, 2010 at 10:35 PM

Thanks for the quick reply. I have read up on templates and styles and believe that I have a basic understanding of what they do.

I have followed your suggestion and put {TemplateBinding Background} into the rectangle which defines the background:

<Rectangle Grid.RowSpan="2" RadiusX="3" RadiusY="3">
    <Rectangle.Fill>
        <LinearGradientBrush StartPoint="1,0.5" EndPoint="0,0.5">
            <GradientStop Offset="0" Color="{TemplateBinding Background}" />
            <GradientStop Offset="1" Color="{TemplateBinding Background}" />
        </LinearGradientBrush>
    </Rectangle.Fill>
</Rectangle>

However, I still can't seem to access this Background property outside of the ControlTemplate. I have tried setting the Background property in the styles and also in my swc:Window element with no luck. Can you please give me some more advice as to where I'm going wrong?

Feb 15, 2010 at 1:27 AM

Ok after a bit more playing around I've managed to solve the background color issue with the following simplification of the code:

<Rectangle Grid.RowSpan="2" RadiusX="3" RadiusY="3" Fill="{TemplateBinding Background}" />