#938 – Changing the Selected Text Color in a TextBox

You can change the color of the brush that is used to show selected text in a TextBox by setting the SelectionBrush property.  You’ll typically set this property in XAML to the name of the color that you want the text selection rendered in.  This property defaults to a SolidColorBrush whose color is hex 3399FF (R=51, G=153, B=255), or light blue.

        <TextBox Name="txtTest" Margin="5" Height="100"
            Text="{Binding SomeText}"
            TextWrapping="Wrap"
            SelectionBrush="Purple"
            VerticalScrollBarVisibility="Auto"/>

938-001
The opacity used by the selection brush defaults to 0.4, but you can set it to be more (>0.4) or less (<0.4) opaque by changing the SelectionOpacity property.

        <TextBox Name="txtTest" Margin="5" Height="100"
            Text="{Binding SomeText}"
            TextWrapping="Wrap"
            SelectionBrush="Purple"
            SelectionOpacity="0.2"
            VerticalScrollBarVisibility="Auto"/>

938-002

Advertisement

#809 – You Can Use a Brush for a Control’s Background

A control’s Background property dictates how the background of the control is rendered.  It is set to an instance of a Brush object.  The two most common types of brushes are solid color brushes (SolidColorBrush) and brushes painted with a color gradient (GradientBrush).

You can use the shortcut of specifying one of the predefined colors for the value of the Background property.  This will cause the background to be rendered with a predefined SolidColorBrush of the specified color.

    <StackPanel>
        <Label Content="Hemingway" HorizontalAlignment="Center"
               Background="LightBlue"/>
        <Label Content="Fitzgerald" HorizontalAlignment="Center"
               Background="Thistle"/>
    </StackPanel>

809-001
You can also explicitly define a brush. The example below uses a LinearGradientBrush that ranges between two colors.

        <Label Content="Hemingway and Fitgerald" HorizontalAlignment="Center"
               Padding="20,10" Margin="10">
            <Label.Background>
                <LinearGradientBrush>
                    <GradientStop Color="LightBlue" Offset="0.0"/>
                    <GradientStop Color="Thistle" Offset="1.0"/>
                </LinearGradientBrush>
            </Label.Background>
        </Label>

809-002

#550 – Converting a Brush into a Resource in Blend

Once you spend some time creating a Brush in Blend, e.g. specifying the different colors in a gradient brush, it’s likely that you’ll want to use the same brush in several different spots in your user interface.  You could just copy/paste the definition of the brush in XAML.  But the easier way to reuse a brush is to convert it to a resource and then to reference the resource by name wherever you use it.

To start with, assume that we have a linear gradient brush defined for a Label control’s Background.

Start by clicking on the white square (Advanced Options) to the right of the brush-related property.

On the menu that comes up, select Convert to New Resource.

Specify a name for the new resource.

Notice that the XAML now defines the brush as a resource and then references it from the Label.

#231 – You Can Use a Brush for a Control’s Foreground

Though brushes in WPF are most often used to fill in the background for a window or a control,  you can also render the foreground of many controls using a brush.

For example, we can use a brush instead of a solid color for the Foreground property of a Label.  The text of the label will be rendered in a specified font and the body of the letters will be rendered using the specified brush.

		<Label Content="You can render text with a brush.." HorizontalAlignment="Center" Margin="20"
			   FontSize="24" FontWeight="Bold">
			<Label.Foreground>
				<LinearGradientBrush StartPoint="0,0.5" EndPoint="1.0,0.5">
					<GradientStop Color="DarkSlateBlue" Offset="0.0"/>
					<GradientStop Color="SkyBlue" Offset="1.0"/>
				</LinearGradientBrush>
			</Label.Foreground>
		</Label>

#221 – Changing a Brush at Run-Time

You can change aspects of a Brush, such as its color, at run-time and any objects that use that brush will automatically be redrawn.

Let’s say that we have several controls in a window that make use of a SolidColorBrush:

	<Window.Resources>
		<SolidColorBrush x:Key="magicBrush" Color="Red"/>
	</Window.Resources>

	<StackPanel>
		<Button Content="Don't Push Me" Background="{StaticResource magicBrush}" Width="120" Margin="10"/>
		<Label Content="Pull my finger!" Foreground="{StaticResource magicBrush}" HorizontalAlignment="Center"/>
		<Ellipse Height="100" Width="200" Fill="{StaticResource magicBrush}" Margin="10"/>
	</StackPanel>

.

Now assume that we change the Color property of the brush at run-time:

    SolidColorBrush magicBrush = (SolidColorBrush)this.Resources["magicBrush"];
    magicBrush.Color = Colors.Purple;

When you do this, you’ll notice that the color in all of the controls changes as soon as this code executes.

All of the controls update immediately because SolidColorBrush derives from Freezable, which supports the Changed event.  The Changed event fires when the color changes and the controls handle that event and redraw themselves.

#214 – Starting/Ending a Gradient Fill Inside a Control

You typically set the StartPoint and EndPoint of a gradient fill at the control’s boundary.  For example, a red-blue gradient might start at the left edge of the control and end at the right edge.  This is done with a StartPoint of (0,0.5) and an EndPoint of (1,0.5).

You can also specify start and end points that are in the interior of the control.  If we specify (0.33,0.5) as the StartPoint and (0.67,0.5) as the EndPoint, we get the following.  (Gradient line drawn, for reference).

We still have a red-to-blue gradient, but the gradient starts 1/3 of the way into the rectangle and finishes 2/3 of the way into the rectangle.

The fill behavior outside the specified gradient line depends on the value of the GradientBrush.SpreadMethod.  The default for this property, GradientSpreadMethod.Pad, specifies that the color at the edge of the gradient should just be extended to the edge of the control.

#212 – Creating a Linear Gradient Brush

Whenever WPF expects a Brush, e.g. for a control’s Background property, you can use a linear gradient brush rather than a solid color brush.

A linear gradient is a fill style that fills an area with a pattern that starts out as one color and gradually changes to one or more other colors.

A linear gradient changes colors along a gradient line.  By default, this line extends from the upper left corner down to the lower right corner of the area being filled.

You specify the colors to be used by defining a series of gradient stops.  Each stop describes the color to use and an offset (0.0 to 1.0) indicating how far along the gradient line that color will appear.

Here’s an example, with the gradient changing from red to blue.

        <Button Height="100" Width="200" Content="A button" Margin="10">
            <Button.Background>
                <LinearGradientBrush>
                    <GradientStop Color="Red" Offset="0.0"/>
                    <GradientStop Color="Blue" Offset="1.0"/>
                </LinearGradientBrush>
            </Button.Background>
        </Button>

#210 – Specifying Colors in XAML As RGB Values

The type converter that converters names of colors to a SolidColorBrush of the specified color will also create a brush of a specified RGB color.  You can specify RGB color values in XAML in one of several ways.

In the example below, we specify each of the R, G and B values as a 2 hex-digit number (00-FF), representing the range 0-255.  The digits are ordered RRGGBB, so the value #FF0000 is solid red.

        <Button Height="25" Width="100" Content="A button" Background="#FF0000"/>

Here are some other formats that you can use:

  • #rgb – RGB value with only 1 digit per color (0-F).  E.g. #FF0 (Red+Green = Yellow)
  • #argb – single-digit RGB + alpha value (0-F)
  • #aarrggbb – 2 digits for R, G, B + 2 digits for alpha channel (transparency)
  • sc#scA,scR,scG,scB – scRGB formatted number, each value ranging from 0.0 to 1.0

#209 – Specifying a Color Where a Brush Is Expected in XAML

We saw earlier how to set the Background property for a control in XAML, by setting the property to an instance of a SolidColorBrush and then setting the Color property for the brush:

    <Window.Background>
        <SolidColorBrush Color="PowderBlue"/>
    </Window.Background>

We can be much more concise than this, however, just setting the value of the Background property directly to a color:

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="346" Width="590"
        Background="PowderBlue">

This works through the use of type converters.  The Background property uses a type converter to convert a string to an instance of a SolidColorBrush of the corresponding color.  Specifically, it sets the property to point to the preexisting Brushes.PowderBlue brush.  You can see the full list of predefined brushes here.

#172 – Changes to a Brush Cascade to Consumers of the Brush

If you create a Brush object, in XAML or code, and use that Brush in some controls, any changes to the original Brush are automatically reflected in controls that use the brush.

For example, assume that we define a teal SolidColorBrush as a resource and use it to render a Label.

    <Window.Resources>
        <SolidColorBrush x:Key="tealBrush" Color="Teal"/>
    </Window.Resources>
    <StackPanel>
        <Label Content="I'm teal!" Foreground="{StaticResource tealBrush}"/>
    </StackPanel>

Now assume that we change the brush’s color at runtime:

            SolidColorBrush theBrush = (SolidColorBrush)this.Resources["tealBrush"];
            theBrush.Color = Colors.DarkMagenta;

You’ll see that the foreground color of the Label changes immediately, as soon as we change the color of the brush.

This change notification behavior is true not only of the Brush class, but of all other classes used in rendering WPF graphics.