in

vbCity Blogs

New (temp) place for vbCity Blogs

Ged Mead's Blog

March 2009 - Posts

  • Colors and Brushes in WPF

     

      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.

  • Visual Basic Code Samples on MSDN

      If you develop in Visual Basic (and if you are reading this blog, I guess you do!) then you'll be as painfully aware as the rest of us that the number of VB samples on MSDN seems to be dwindling away. There was a time when you could guarantee that all the samples would be shown in both C# and VB. Not any more. These days, too many of the new articles come with C# only samples.

     

      And before you reach for your keyboard to tell me that it's a trivial task to run the C# through a code converter, I suggest that you try it first. There are some excellent converters out there, but understandably they have to catch up with the newest technologies before they can achieve 100% accuracy. So when you try and convert the latest code from C# to VB this way, you often get results that don't cut it.

      Anyway, the good news is that Microsoft are aware of this worrying trend and moves are afoot to ensure that the slide to C# only code samples is stopped. A good example is the Microsoft Patterns & Practices’ Composite Application Guidance for WPF and Silverlight (formerly code-named "Prism"). Initially there were no VB versions of the QuickStarts, Hands-On Labs, and How-to Topics. Happily, this omission is now being fixed and the download can be reached here.

      I always stay away from the silly "Which is better - VB or C#" arguments. I believe that each language happens to suit a different type of mindset and neither is better nor worse than the other. But as Microsoft create and sell both versions on an equal footing, it does seem only right that they support them both with the same kind of equality. I hope there will be many more examples of, well, examples coming our way in the future!

  • Removing Quotation Marks (Double Quotes) From a Text File

     

      Sometimes you don't have control over how the data is saved to a text file. For instance, some items might be saved with quotation marks around words or phrases. If you want to read the file but not show these marks then you'll need a way to remove them.

      Like a lot of things, it's actually very easy when you know how. You can use the built-in Replace function of the String class, replacing the marks as you find them. The trick though (and to my mind, the less than totally intuitive bit) is knowing how many quotation marks to use in the first argument of the Replace method's parameters. This is the 'OldChar' parameter, i.e the one you want to replace.

      You would think, wouldn't you, that you could put a Quotation Mark inside a pair of Quotation Marks like this:-

     

    Code Copy
    MyString.Replace(""", "")

     

      But if you try that, you will find that it doesn't work. What you actually have to do is include a second Quotation Mark inside the outside ones. In other words, you need four Quotation Marks in a row.

     

    Code Copy
    MyString.Replace("""", "")

     

      It's only a tiny change, but it will move your mental state from annoyed confusion to enlightened contentment. Or something like that, anyway.

      So putting this together with code that reads from a file and displays the result (minus Quotation Marks) in a ListBox, you have:

     

    Code Copy
    Private Sub RemoveQuotes(ByVal filename As String, ByVal target As ListBox)
            '  A StreamReader to fetch the data
            Dim sr As New IO.StreamReader(filename)
            '  A string to hold each line as it is read
            Dim line As String = String.Empty

            ' Read from the file
            ' As long as there is something left to read
            Do While sr.Peek <> -1
                ' Replace the Quotation Marks with Nothing
                line = sr.ReadLine.Replace("""", "")

                ' Add edited text to a ListBox
                target.Items.Add(line)
            Loop

            '  Tidy up when finished
            sr.Close()
            sr = Nothing
    End
    Sub

     

      If you prefer your code to be broken down into clearer steps, you could do this instead:

     

    Code Copy
        Private Sub RemoveQuotes(ByVal filename As String, ByVal target As ListBox)
            '  A StreamReader to fetch the data
            Dim sr As New IO.StreamReader(filename)
            '  A string to hold each line as it is read
            Dim line As String = String.Empty

            ' Read from the file
            ' As long as there is something left to read
            Do While sr.Peek <> -1
                '  Read the next line
                line = sr.ReadLine

                ' Replace the Quotation Marks with Nothing
            line = line.Replace("""", "")

                ' Add edited text to a ListBox
                target.Items.Add(line)
            Loop

            '  Tidy up when finished
            sr.Close()
            sr = Nothing
        End Sub

     

      Either way, your quotation marks will be history.

  • Copying An Item Between ListViews

     

      I've always found ListViews quite fascinating. Slightly confusing sometimes, but fascinating nevertheless.

      As I have often been heard to say, it's the little things that'll trip you up.     Take, for instance, the subject of this blog - copying an item between ListViews. The scenario is that you let the user click on an item in ListView1 and if they want this item copied to ListView2, they hit a button.

    Now, you would probably think that all you need to do is identify the currently selected item and add it straight to the second ListView. Something like:

     Code Copy

    ListView2.Items.Add(ListView1.SelectedItems(0))

     

      But if you do try this, you will get an error.

     

      

      The text of the error message pretty much says it all. What you have to do (assuming that you aren't prepared to remove the item from the original ListView) is to clone it. You will then be allowed to add the clone to the second ListView.

      Although the cloning isn't difficult, you do have to be aware of the need to cast the selected item to ListViewItem if you have Option Strict On. To be honest, I found this a bit strange at first. If I lift a ListViewItem from a ListView, I didn't expect to have to cast it to what it is - i.e a ListViewItem.

      I'm not entirely sure why this occurs and wonder if the underlying reason for this is that the ListViewItem is stored in the SelectedItems collection of the ListView as a generic object. Anyway, Casting it back to a ListViewItem at the point where the cloning takes place, fixes this without any problem.

      This code works well:

     

    Code Copy
    If ListView1.SelectedItems.Count > 0 Then
        Dim lvi As New ListViewItem
        lvi = ListView1.SelectedItems(0)
        Dim lvi2 As New ListViewItem
        lvi2 = CType(lvi.Clone, ListViewItem)
        ListView2.Items.Add(lvi2)
    End If

     

      You'll have noticed that I built in a test to ensure that an item is currently selected. It's an easy thing to forget and is sure to bring your app to a grinding halt before long if you don't build this in.

      You can see where I have cast the selected item (aka lvi) to ListViewItem in Line 5. Intriguingly, casting to ListViewItem in the third line of code, e.g.

      Code Copy

    lvi = CType(ListView1.SelectedItems(0), ListViewItem)

       doesn't cut it.

        

  • Moving From VB6 to VB.NET

     

      There are millions of successful VB6 applications out there in the world. There they sit, happily whirring away doing whatever it is they do - perhaps occasionally being maintained or tweaked by an army of developers.

      But there is no getting away from the fact that somewhere under the surface there is gentle but insistent pressure for developers and companies to move up from classic VB to the .NET platform. There are many reasons for this pressure, some valid, some not quite so. Some people believe that the almost total migration to .NET is almost inevitable eventually, so why fight it. The benefits offered by an ever-widening platform can't be ignored for ever, others say. Some just like to change to whatever is shiny and new, because, well just because it's shiny and new - not a realistic option for most businesses at any time and certainly not in the depths of 2009.

      It's contended that it is becoming more difficult to recruit and retain skilled Visual Basic 6.0 developers. Academic institutions and training departments are moving to .NET. The internet is all pervasive. VB6's abilities with internet related tasks is limited.

      Lots of reasons then. But what's a girl (er, I mean What's a company) to do?

      Change is rarely easy to implement or comfortable to face and no-one who knows what they're talking about is going to pretend that the change from classic VB to VB.NET is simple. It's not. But neither is it anywhere near impossible. And the really good news is that as time has gone on, more and more upgrade tools - tools, that really do work now, by the way - are becoming available.

      The Upgrade Wizard in VS2008 is far better than the earlier efforts. The Interop Forms Toolkit gives you a fighting chance of combining classic VB with VB.NET. Commercial tools have been developed, used, tested, improved and are now available.

      So, if you are one of the many who have been thinking about maybe, just maybe, migrating from VB6 to VB.NET then you will probably be interested in this article - Secure Your Visual Basic 6 Investment with Microsoft.NET. As you will see, it covers a lot of ground, describes the options, includes advice and the experience of companies who have made the upgrade and lived to tell the tale.

      I was going to finish this off by saying something like - "Go on! You won't regret it!" But honesty forces me to say that at times you almost certainly will. Let's face it, most of us get very frustrated when we are pulled out of our comfort zones and find ourselves battling with something that we're not even sure we wanted in the first place. It's so much easier to just keep doing what you find easy. But, like so many things that take a lot of effort, I am sure that once you have got over the hurdles you will stop, look back, nod to yourself and say "You know, I'm glad I did that. It was worth the effort"

Copyright 1998-2009 vbCity.com LLC
Powered by Community Server (Non-Commercial Edition), by Telligent Systems