XTab's Blog

Ged Mead's Blog at vbCity

vbCity Blogs moved to:
http://cs.vbcity.com/blogs
  Home :: Syndication  :: Login

SepOctober 2008Nov
SMTWTFS
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

Archives

Topics

Ramblings

VB.NET

Thursday, October 23, 2008 #

  One of the things that first caught me out in WPF was the simple topic of colors. For example, let's say you want to reset the BackColor of a Form in Windows Forms.

Easy enough. This will do the job:

Code Copy
Me.BackColor = Color.CadetBlue

 When it comes to WPF, you'll know that we are dealing with a Window, instead of a Form and have probably already picked up that BackColor is now Background.  You can however, still use "Me" to reference the Window.

 But if you were to try something like:

Code Copy
Me.Background = Color.CadetBlue
    ' or even
Me.Background = Colors.CadetBlue

you would be disappointed.

 You would however get some help from Intellisense (at least with the second version). The error message tells you that a Color cannot be converted to a Brush. And there's the answer to the problem.

The Background property doesn't take a Color - it takes a Brush, which of course can, and usually does, have a color assigned to it. Don't forget though that you are not limited to a single solid color; there are many gradient, tile and image based options that you can choose when it comes to brushes in WPF.

 So this code will work fine in WPF:

Code Copy
  Me.Background = New SolidColorBrush((Colors.CadetBlue))


 Ah yes, I hear you say, but what about the theory that you should use XAML for the look and code-behind for the behaviour? Well, I can't disagree with you there and personally I would use:


<Window x:Class="Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300" 
Background="CadetBlue">


 where the Background property for the Window is set there in the XAML. However, there may well be times when you want the user to have a say in color choices and in those cases it can be easier to take the user's input and deal with it in the code-behind.

  For example, if the user was empowered to enter values for the ARGB components then you might use an approach like the following:

Code Copy
        Dim col As New System.Windows.Media.Color
        '  In reality the values below could be
        ' selected by the user and passed in
        col = Color.FromArgb(214, 122, 52, 24)
        Dim br As New SolidColorBrush(col)
        Me.Background = br

  

   It would also be quite easy to create a display in WPF where you bind, for example, sliders to the Brush that is used for the background. But I won't go any deeper into that just now, as this sub-set of blog items is meant only to help identify those missing WinForms favorites and repatriate them as WPF troops.

posted @ 8:56 PM | Feedback (0)