Wednesday, March 24, 2010

WPF BorderBrush

This article demonstrates the way to work with WPF BorderBrush.

The Border control in WPF is used to draw a border along the edges of a control. The Border control has a property named BorderBrush which is the drawing brush for the border.

The way we declare the BorderBrush in XAML is different than through code. As we know, XAML automatically converts string to a specific type.
The following code demonstrates use of the Border element,
<StackPanel>
    <Border BorderBrush="Blue">
       <TextBox>Dummy text</TextBox> 
    </Border>    
</StackPanel>

The above code has a StackPanel containing a Border for a TextBox. The BorderBursh is assigned a Blue color. This means, the Border will be a SolidColorBrush of Blue color. SolidColorBrush is the default WPF Brush.

Now, we will see how to interact with the BorderBrush in code-behind. The scenario we will look at is, finding the current color of the BorderBrush and if Blue then changing it to Red. The following code demonstrates the same,
Color clr = (brdr.BorderBrush as SolidColorBrush).Color;
if (clr.Equals(Colors.Blue))
    brdr.BorderBrush = new SolidColorBrush(Color.Red);