C# WPF XAML Background Colour


In your Windows program, how do you set the background colour of a control, such as a rectangle, using XAML?

The XAML code below shows you how to set a custom colour using XAML.

<Rectangle Name="Rect" HorizontalAlignment="Left" Height="185" Stroke="Black" VerticalAlignment="Top" Width="71" Canvas.Left="416" Canvas.Top="65">
    <Rectangle.Fill>
        <SolidColorBrush>
            <SolidColorBrush.Color>
             <!-- Describes the brush's color using  RGB values. Each value has a range of 0-255.  
             R is for red, G is for green, and B is for blue.  A is for alpha which controls 
             transparency of the color. Therefore, to make a completely transparent
             color (invisible), use a value of 0 for Alpha. -->
                <Color>
                    <Color.A>255</Color.A>
                    <Color.R>100</Color.R>
                    <Color.G>200</Color.G>
                    <Color.B>150</Color.B>
                </Color>
            </SolidColorBrush.Color>
        </SolidColorBrush>
    </Rectangle.Fill>
</Rectangle>

The next question is how do you allow the user of the program to set the colour of the rectangle? You could provide three text boxes for them to enter in the values. Have a look at a more complete program at this post called RGB Colour Viewer.

Leave a comment

Your email address will not be published. Required fields are marked *