Category Archives: C#

The WPF Button

It’s finally time to quit talking about WPF Containers, and start getting into some of the controls. The first one we’ll hit is the hardest working control in show business, the WPF Button.

I’m sure you’re thinking “what’s so hard about a button?” After all, you slap a button tag on a form like this:

<Window x:Class=WPFSample001.ButtonWindow

    xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

    xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml

    Title=Buttons Height=83 Width=194

    >

  <StackPanel>

    <Button>Click Me Baby!</Button>

  </StackPanel>

</Window>

I created a window named ButtonWindow, and added a StackPanel with one button. This will give you something like this:

wpf022 

Simple and easy, but there’s much more to the button. First off, you can change the point at which the click event actually fires. The button has a ClickMode property you can set that controls this. The default is “Release”, which pretty much acts as you expect. The other two values are Press and Hover. When the button looks like a button, you would probably want to use release, however it’s possible to morph the button to a graphic of some sort. In that case it might be more intuitive to fire when the button is first pressed, and not when the user releases the mouse.

Speaking of the click, just how do you react to a WPF event in C# anyway? Good question, I thought you’d never ask.

All you have to do is indicate the name of the event you want to respond to, then pass in a string value which is the name of the method to route to. In your XAML, alter the Button line to look like this:

      <Button Click=Baby_Click>Click Me Baby!</Button>

 

Now we need a little C# code to respond. Open the code behind class (in my case ButtonWindow.xaml.cs). Now add a new method:

    private void Baby_Click(object sender, RoutedEventArgs e)

    {

      MessageBox.Show(“Hi There!”,“Baby was clicked!”);

    }

WPF Events must match a certain signature. They will need to have a return type of void (or will be a SUB for you VB folks). They will also accept two arguments, an object that indicates what the sender of the event was, and a set of event arguments encased in the RoutedEventArgs variable, traditionally called e.

Here were doing something pretty simple, and showing a message box.

wpf023 

There’s lots more we can do with the button, but we’ll save that for a more advanced day. Today I just wanted to cover the basics of the button, as it’s one control that will likely see a lot of use in your toolbox.

Advertisements

Starting a WPF Project

Head colds are nasty things. Yeah, I know folks like Scott Hanselman and Jeff Atwood say we shouldn’t talk much about ourselves, but I offer this as explanation for dropping off the face of the earth last week. A nasty head cold, followed by busy work week and my houses air conditioning dying in the middle of an Alabama triple digit heat wave… well something had to give.

But hey, odds are you’re not hear to offer your chicken soup recipe, but find out about WPF. So let’s kick this week off by starting a WPF project. Assuming you followed my instructions in my last post ( https://arcanecode.wordpress.com/2007/08/20/installing-the-wpf-bits/ ), you now have all the bits installed. Open Visual Studio 2005, and create a new project.

In your “New Project” window, navigate down to the “NET Framework 3.0” branch. In the templates area you see some new ones. One, WCF Service Library, is for creating Windows Communication Services projects and is outside the scope of this discussion.

The other three are WPF oriented projects. Windows Application (WPF) is for creating general windows applications using WPF. This is what you’ll probably use the most, and what we’ll pick for today’s demo. I named mine WPFSample001, as you can see above.

Before you click OK, let me just mention the other two. Custom Control Library (WPF) is analogus to it’s “old fashioned” WinForms counterpart. It lets you create a custom control comprised of WPF pieces for use in WPF Windows projects.

XAML Browser Application (WPF) is used to create a WPF App that will run inside a browser. Note this isn’t Silverlight. This is more like a Click Once deployment that opens the app inside the browser. MSDN (Sep 2007) had a good example of one you can see for yourself at http://ttpdownload.bl.uk/browserapp.xbap .

OK, that covers the various WPF project types. For today, we’ve decided on a standard WPF Windows Application, so click OK as you see in the screen above.

Let’s take a quick tour of what you see. Over on the left is the Toolbox. Under Common Controls, we see some with names look familiar. Button, CheckBox, Lable, etc. These are the WPF versions of the old Windows Forms controls. There are some new controls too, such as the DockPanel, the StackPanel, and a Grid which is unlike any Grid you’ve used in the past. We’ll get into these as time goes by.

Over on the right, in the Solution Explorer you see the Files that make our WPF project. App.xaml (and it’s corresponding App.xaml.cs) is the starting point for our Windows WPF app. Here you can respond to events like application starting and stopping, or you can blissfully ignore it.

The Window1.xaml is your main focus now, since it’s where you can do all your work. If you look at the center pane, you’ll notice it’s a bit different from traditional Windows Forms or even ASP.Net designer, in that it gives you the nice split screen. Changes in one are reflected in the other.

If you don’t like the split, you can modify it by either moving the mouse in the middle area and adjusting where the spit occurs, or manipulate it using the controls on the right side of the tab area:

The left most button flips the split from the default horizontal to a vertical one, nice if you have a really wide screen monitor. The middle button returns the split to the default horizontal orientation. The right most button removes the split all together, putting two tabs at the bottom (one for designer, one for xaml), not unlike the experience you get today when designing ASP.Net html pages.

Before I close out today, I want to mention that the designer tool under 2005 is not fully baked. You will see a lot of “whoops” screens appear. In addition, control placement is more like the ASP.Net experience than WinForms. As such, most folks I’ve seen so far prefer to type the XAML code directly in.

To start with I’ll be doing just that, typing in the XAML which will help me learn the behind the scenes syntax. Later I’ll shift to using the Expression Blend tool as the main XAML designer.

This is a good start, tomorrow we’ll pick up with creating a simple XAML app.

Arcane Searching

I think we’d all agree the internet is one of the greatest productivity tools around, allowing us to find vast stores of information. I’m sure you’ve also heard it’s the greatest time waster, with lots of distracting sites or useless pages that get in the way of the results we want.

I find it really valuable to have a good search tool, one that focuses on the content I need, and limits the scope of the search to relevant areas. Of course we’ve all heard of Google, the 500 pound gorilla of search engines. While the do a pretty decent job, when your search phrase returns half a million hits it can be difficult to narrow down.

Recently I’ve found the Microsoft engine, Windows Live ( http://www.live.com/ ), has gotten a lot better, especially when looking for .Net related developer content.

My favorite so far though, is Search.Net ( http://searchdotnet.com/ ), a site put together by coding legend Dan Appleman. Dan ( http://www.desaware.com/ ) created a Google powered site, but maintains the list of sites it searches so you know that you are only combing sites devoted to programming and not Happy Harry’s House of Wild Women.

Another site I just learned about this week is Koders ( http://www.koders.com/ ). It’s a site devoted to searching through source code. It also has some helps that will let you zoom in on what you want. You can pick the language, or specify your search word needs to be in the class name, method name, or interface name. This kind of search is valuable when you are looking for an example, or trying to avoid reinventing the wheel.

A similar site is Krugle ( http://www.krugle.com/ ). It has similar paradigm to Koders, allowing you to search through code.

The final code search tool I’ll mention is Google’s new Code Search engine ( http://www.google.com/codesearch?hl=en ). It allows you to search using regular expression syntax, which is a nice feature (I just wish regular expressions weren’t such a pain in the underwear to use).

I have to give a quick thanks, most of these I learned about through either my listening of Dot Net Rocks ( http://www.dotnetrocks.com/ ) and HanselMinutes ( http://www.hanselminutes.com/ ) or through Scott Hanselman’s new forum site, which I blogged about yesterday.

Those are the list of place I go when I need to find something, how about you?

Arcane Add-Ins: KNOCKS Solutions VS 2005 Add-In

It’s been a while since I talked about Visual Studio add-ins, so when I ran across KNOCKS Solutions “Knocks VS2005 Add-In”, I knew I’d found the perfect subject. Available at http://www.knocks-solutions.com/VS2005Addins.aspx?sm=idVS20052 , this rather full featured add-in offers many utilities.

First is a personal clipboard, that allows you to store and retrieve up to 9 different items. And they’re persistent, they will stay between VS sessions.

Next is a code snippets manager. This seems a bit redundant in light of VS 2005’s snippets, but I can see it being very useful during a presentation.

In addition to the code snippets is a Notes module. I’ve often wished for the ability to store quick notes to use in a presentation, so this is a handy module.

Up next is the one tool of theirs I have a beef with, the “Re-arrange code” tool. I like the idea of being able to re-arrange my code. Often I’m working on some public method, and realize I need a private helper method and, being in a hurry and lazy, will drop it right under the public method. Later I’ll move it around, which was why I was excited to see this tool.

Sadly, it has a really bad side affect, it strips out any regions you’ve put into your code, and it strips out any comments that might lie between methods (I often put a comment header right above my method, instead of in the method.) When Knocks rearranges your code all of that goes into the bit bucket, making the tool useless in all but (perhaps) the very earliest stages of coding. I would have thought it possible to add regions to the tool as well, and allow code rearranging within a region, between regions, or even to move regions around. Perhaps this will be addressed in the next version (he said, ever full of eternal hope).

There is a nifty zip tool that will zip your entire project, handy for quick backups. Also is a tool that embraces the concept of a favorites for projects. Another tool is one I wonder why no one did sooner, a keyword search on Google (or other configurable search engine, like MS Live). This is one I’ll be using often.

Also included is a simple “Data Object” generator. You bring it up and enter a few property names and types and Knocks will create the basic class for you. While I have seen more full featured code generators, I appreciate the basic simplicity of this one, not to mention the price (which I’ll get to shortly).

knocks01The final two tools I’ll mention are my favorites. First is a Design Explorer. This adds an explorer window (I put mine with the Solution Explorer area) to your display. In it are all the controls for your current form. Clicking on the control not only makes it the active control in the designer, but displays the properties in the lower half of the Design Explorer window.

 

 

 

 

 

 

 

 

 

knocks02The other tool is the Code Explorer. It displays a tree of your current code module. Double clicking on the code element will take you to it in the code window.

I’ve seen other add-ins with code windows, this one seems equal in functionality with many others similarly priced.

 

 

 

 

Oh, did I forget to mention the price? It’s free. Yes, FREE. Knocks has packed a lot of functionality into this add-in, and the fact it’s free makes it well worth the time to download and learn.

Arcane Talks

On Thursday July 12th I’ll be speaking at the Birmingham Software Developers Association (BSDA). You can get directions from the club’s website, http://www.bsda.info/ .

I’ll be speaking on the subject of SQL Server Compact Edition. It’s been a while since I blogged about this, so I thought I’d provide a few links for quick reference.

As promised, here is a link to the Power Point presentation (in PDF format) I used during the presentation:

 SSCE presentation for BSDA user group

My very first post was back in January 2007:

http://shrinkster.com/nsk

My next series of posts began on April 10th, and described how to create databases using the various tools available to you.

http://shrinkster.com/qtl

The complete C# and VB.Net code samples were posted April 13th, 2007:

http://shrinkster.com/qtm

And finally, the series of posts I mentioned on system Views started with this post on April 16th, 2007:

http://shrinkster.com/qtn

If you want to see all of my SSCE posts, simply click the SQL Server Compact Edition tag over in the categories area, or use this link:

 https://arcanecode.wordpress.com/tag/sql-server-compact-edition/

Please note each of these links is a starting point, be sure to read the blog for the next few days after each link in order to get the full story.

And now a question, I’m working up material for a new presentation. Debating between SQL Server 2005 Full Text Searching and SQL Server Integration Services. Any opinions?

Eventually I’ll do both, but would like to do the first one based on feedback. Even if you can’t attend please post a comment and let me know where your interests lie.

Collections in C#: NameValueCollection

In doing some reading I ran across a handy collection called the NameValueCollection. This collection, which resides in the System.Collections.Specialized namespace, allows you to use either a string or an integer index for the key. Further, it allows you to store more than one string value in a key.

Let’s start the code example by creating a simple Console application. I added using references to System.Collections and System.Collections.Specialized namespaces at the top. As a final bit of housekeeping, make sure to add a Console.ReadLine() as the last line of our code, so the console will wait on us to hit the enter key after we read the results. (If you don’t, the program will run so fast you won’t be able to appreciate your fine work.)

Now I’m going to load some data into a new collection called myCollection. For the data, I’ll use a website owner and the website or sites they own.

      System.Collections.Specialized.NameValueCollection myCollection

        = new System.Collections.Specialized.NameValueCollection();

 

      myCollection.Add(“Arcane”, http://arcanecode.com&#8221;);

      myCollection.Add(“PWOP”, http://dotnetrocks.com&#8221;);

      myCollection.Add(“PWOP”, http://dnrtv.com&#8221;);

      myCollection.Add(“PWOP”, http://www.hanselminutes.com&#8221;);

      myCollection.Add(“TWIT”, http://www.twit.tv&#8221;);

      myCollection.Add(“TWIT”, http://www.twit.tv/SN&#8221;);

Next, I’d like to get some data back out. I mentioned you could cycle through the collection using an integer index, so let’s see how that’s done:

      Console.WriteLine(“Key / Value Pairs by Integer Index”);

      for (int i = 0; i < myCollection.Count; i++)

      {

        Console.WriteLine(i.ToString() + ” “

          + myCollection.GetKey(i) + “: “

          + myCollection.Get(i));

      }

 

[Picture of Key/Value pairs by Integer Index]

 

In the above output you can see how I use the GetKey and Get methods to retrieve the key name and value for that key using the loop’s index. Note that when multiple values are associated with a single key, they are returned as a list of comma separated values.

You can also use foreach logic to cycle through the collection. Here I am using the AllKeys property of our collection to get the list of keys. I can then print the key, and also use the key as the indexer into my collection as you can see below.

      Console.WriteLine();

      Console.WriteLine(“Keys / Value Pairs via AllKeys Collection”);

      foreach (string myKey in myCollection.AllKeys)

      {

        Console.WriteLine(myKey + “: “ + myCollection[myKey]);

      }

 

[Picture of Key/Value pairs via AllKeys Collection]

 

Now I, what? Yes, you in the back row, what was your question? Ah, you say lists of comma separated values are OK, but you want to be able to access individual values? Fortunately some nested looping and the GetValues method will satisfy you demanding types.

 

      Console.WriteLine();

      Console.WriteLine(“Keys / Individual Values”);

      foreach (string myKey in myCollection.AllKeys)

      {

        foreach (string myValue in myCollection.GetValues(myKey))

        {

          Console.WriteLine(myKey + “: “ + myValue);

        }

      }

 

[Picture of Keys/Individual Values]

 

This also works great if your data has commas within it. Let’s add two lines back at the top of the program to the collection.

      myCollection.Add(“CommaTest”, “Here is a , in a string”);

      myCollection.Add(“CommaTest”, “Here is another , in a string”);

 
Now run the application again, and lets look at the results.
 
[Picture of Comma Test]

As you can see in the last area “Keys / Individual Values” the GetValues method correctly determined that the commas I had embedded were part of the data and not a delimiter between values.

Whenever you need a good string collection that has the ability to tie multiple values to a single key, the NameValueCollection would be a good class to take a look at.

 

Arcane Tools: Cropper

Well, the uber cool Scott Hanselman has done it again, found another gem. OK, he’s been using it for a while, but in watching his GrokTalk ( see my post on Tuesday ) I learned about Cropper.

Cropper is a screen capture tool. As you can see below, it puts an translucent window on your screen. You can move and resize this window with the mouse, or the keyboard.

[Pic of Cropper in action]

The arrow keys will move the cropper window in 1 pixel increments for fine tuning, or for quick moves combine the arrows with the CTRL key to make 10 pixel jumps. You can also resize, use ALT plus the arrows for 1 pixel resizes, or CTRL+ALT+arrow for 10 pixel resizing jumps.

You have the option to save in a variety of formats, including BMP, PNG, and JPG, and can even select a level of JPG compression. You can also save to the clipboard if you so desire.

To capture an image, simply double click on the translucent cropper window, or press ENTER. When you do, a file is written to your Documents folder in a subfolder called Cropper Captures (although this is user configurable). I like this, as it lets me quickly grab one screen shot after another without having to put a lot of thought into it.

The coolest thing about Cropper though, is it’s entirely written in C#, and open source so you can see all the code. It comes courtesy of Brian Scott, you can see his blog and download Cropper for yourself at http://blogs.geekdojo.net/brian/articles/Cropper.aspx .

The only negative I’ve found is the name. Apparently cropping is also a popular term in the scrapbooking world, so when I started talking about cropper my wife ( http://southerntinkerbelle.com ) got all excited and tought I was getting into scrapbooking! I hated to disappoint her, but on the bright side the sofa really wasn’t all that uncomfortable.