Page view counter

May 2008 - Posts

Creating a Project from xaml and xaml.cs files

I posted the code for the PageSwitcher app described in a previous blog post, but to save space and to make the download faster, I didn't include anything but the code (no solution or project files). A reader wrote asking how to create a project and it is a more than fair question as the answer is not obvious until you've done it a couple times, so let's walk through that example.

When you download the code, you'll receive a zip file named  PageSwitcher.zip. Unzip that and you'll have a folder named PageSwitcher,

PageSwitcherFiles

 

Open a new Visual Studio project and to make this example as clear as possible, let's name it something else (myPageSwitcher) and locate it in a different directory.

Open Page.xaml in your new project and note the name of the project (MyPageSwitcher)

<UserControl x:Class="MyPageSwitcher.Page"

Open Page.xaml.cs and note the namespace

namespace MyPageSwitcher

This is the information you need to hold on to for the rest of this exercise.

Ready To Go

There are many ways to do this, but the easiest is to delete Page.xaml, Page.xaml.cs and App.xaml and App.xaml.cs from your new project. (Don't panic!)

Next, right-click on the project and choose Add->Existing items and navigate to the downloaded files and add them all. They are now in your new project.

Click on all 4 xaml files and change the name of the project in the x:Class tag.

Click on all 4 .cs files and change the name of the namespace (ignore the smart tag) If you want to get rid of the smart tag, use Build->Clean. Build->Rebuild Solution.

You're all set

Here is your new PageSwitcher.xaml

<UserControl x:Class="MyPageSwitcher.PageSwitcher"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300">

</UserControl>

 

And here is your new PageSwitcher.xaml.cs

using System.Windows.Controls;

namespace MyPageSwitcher
{
    public partial class PageSwitcher : UserControl
    {
        public PageSwitcher()
        {
            InitializeComponent();
            if (this.Content == null)
            {
                this.Content = new Page();
            }
        }
        public void Navigate(UserControl nextPage)
        {
            this.Content = nextPage;
        }
    }
}

 

Don't forget, once your code compiles, you can right click on the using statements and choose Organize Usings -> Remove Unused Using  which greatly cleans up your code.

RemoveUnusedUsing

Blog Post of the Month

Every once in a while I read a blog post that is so good I have to pass it on. Scott Hanselman said it perfectly today.

Posted by jesseliberty | with no comments

Multi-Page Applications in Silverlight

I wanted to build a multi-page (Search - Results) application when I realized that isn't really our model. Fortunately, I wrote to Ashish Shetty , who combines enormous knowledge with enormous kindness, and even though he is in the middle of blogging about this, he agreed that I could blog about it as well. Since I will be creating an HDI Video on this as one of my first Beta 2 videos (RSN) and since I think his solution is wicked cool, here is how you do it

1. Create a new Silverlight 2 project in Visual Studio , (I named mine, MultiPage).

2. You want to have at least three pages. Let's use the default Page.xaml as the first. Add any content you like but  but include a button with a name and set the content to something like "Switch"

3. Right click on the project and click Add New Item, and add a second User Control. Name the new user control anything you want and give it any content you want. I'll call mine Page2.xaml and give it content to make it distinct: 

<UserControl x:Class="MultiPage.Page2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="Beige">
        <StackPanel Orientation="Horizontal">
        <TextBlock Text="This is Page2" FontFamily="Comic Sans MS" 
            FontSize="48" VerticalAlignment="Center" />
        <Button x:Name="SwitcherooButton" Content="Switcheroo" 
            Height="40" Width="80" 
            Background="Red" FontSize="14" 
            Margin="20,0,0,0" />
        </StackPanel>
    </Grid>
</UserControl>

 

Page2Switcher

Note that again I have a button for switching pages.

 

Here is where the magic happens

4. Add a third page (I named mine PageSwitch.xaml.)  Put nothing in the xaml file, because the content will be the page you want to display,  but in the code-behind file add this method:

public void Navigate(UserControl nextPage)
{
    this.Content = nextPage;
}

5. Wire up the buttons on all of your pages to invoke the Navigate method, passing in the page you want to navigate to.

So, in Page.xaml.cs you'll add this code,

public Page()
{
    InitializeComponent();
    SwitchButton.Click +=
          new RoutedEventHandler(SwitchButton_Click);
}
 

void SwitchButton_Click(object sender, RoutedEventArgs e)
{
    PageSwitcher ps = this.Parent as PageSwitcher;
    ps.Navigate(new Page2());
}

 

6. Finally, in App.xaml.cs change the startup page from Page.xaml to PageSwitcher.xaml,

 private void Application_Startup(object sender, StartupEventArgs e)
 {
     this.RootVisual = new PageSwitcher();
 }

 

What's Going On Here??

The way this all works is that when your program starts, the opening page is now PageSwitcher whose content is blank, but whose constructor sets it to whatever you want your first page to be (in this example,  Page.xaml.)  Since all pages are actually user controls, they work fine as the content of a page.

When you click the switch button, you find the parent of your page which is the PageSwitcher page and that has a Navigate method that you invoke, passing in the page you want to navigate to. In this case, we're hardwiring the change, but it wouldn't be hard to make that value be more dynamic.

Navigate causes the PageSwitcher page to change its contents from whichever page it is currently displaying to whichever page you ask it to display, and the garbage collector cleans up the old.

(If you need to keep old values around between switches, create both pages and don't call new, but that will use more memory, or stash the values you need inside member variables of PageSwitcher -- more on that when I do a video on this approach).

 

It is a very cool, very fast effect switching from one page to the other.

SwitchToPage1 SwitchToPage2

 

Here's the complete source code

Twenty Five Years

25 years ago Microsoft Word was released

WordGates

And 25 years ago, today,  I got married.

Today I received this card from my wife...

Marriage1

with this inside

Marriage2

This is the secret to a great marriage and a great company.

What is the point of a survey if....

SurveyMonkey The key point of my survey was to measure your satisfaction and then to make changes to increase satisfaction. I'm pleased that overall satisfaction seems high, but there is always room for improvement.

I will shut down the survey on Sunday and start to review the results in detail.  (Until then, you can take the survey here)

After that I'll make a few changes in how I approach the videos, and I'll conduct another round of surveys later in the summer.

Thanks again for your participation and please don't hesitate to leave comments on any individual video,  or to send me mail with your ideas.

In the meantime, I'm going to experiment with super-short surveys attached to individual videos and tutorials. Perhaps if they're short enough I can get a large enough response base to be meaningful.

Thanks again.

-j

Posted by jesseliberty | with no comments

Xaml vs XAML

I received an email from Ian Griffiths who informed me that  the "Xaml spec refers to Xaml as Xaml, and not XAML." because Rob Relyea didn't like the "shouty caps" look of all upper case. 

After some back and forth, I contacted Rob, who wrote back that Ian is right (no surprise there) but that Rob is "...starting to use XAML" as that ship has sailed.

I don't know, Rob is pretty amazing, (the image below is a link to his blog), and I'm inclined to agree with him that Xaml is a lot classier looking than XAML.

RobRelyea

I suggested that I would put the following note in Programming Silverlight

A quick note on the capitalization of Xaml. Ian Griffiths (who truly knows everything) sent an email that Rob Relyea submitted the official specification with the capitalization as Xaml rather than XAML.  While even Rob agrees that all upper case is the popular usage, his blog, Xamlified (http://tinyurl.com/6h6rr5) is an oasis of camel case,  and high quality information.  This book will use both capitalizations for the sake of inconsistency.

Maybe we can start a movement. I'm going to try. If nothing else, this discussion has led me to find YAAM (Yet Another Amazing Microsoftie) which makes it worthwhile. Keep an eye on his blog; there are gems there.

For those of you about to write that this is a trivial and meaningless distinction not worth the time to blog about... I pretty much agree.

Posted by jesseliberty | 2 comment(s)
Filed under:

Silverlight, Educational Charity and Funny Accents

AussieSite

I love office (as a shareholder) and I live in Word, though I'll keep my thoughts about the ribbon to myself. All of that aside, the Australia Office folks used Silverlight to create a fund raising site on the premise of "sit through a short commercial and we'll give money to education."  Since its Silverlight and Education and Microsoft (three causes I care about) I thought I'd pass it along.

Click here or on the image (that's the picture on the left!)   to watch a (truly cheesy video of an Aussie kid telling you how cool Office is, which you must watch all the way through, but it is short) and Microsoft donates 1 Aussie dollar to education (don't ask me how much that is). It takes 30 seconds, and the site itself is nifty (at least in concept). 

(I like the waving hands; I don't like the fact that the videos take about a year and a half to load, but Australia is very far away.)

Enjoy.

Videos - Interim Opinions...

One of the comments left on the survey said (small excerpt follows)

It is the opinion of my coworkers and I that video tutorials are all a HUGE waste.  We can't sit at work watching hours of video

A perfectly valid, but not universal opinion. It is way too early to report on the survey (only 39 responses so far, I'll have to give some sort of incentive!) but here's a quick rollup (scale of 1-4 where 4 is best)

Question Percent scoring 4 or 5
Topics > 70%
Pacing > 60%
Video & audio quality > 70%
My voice > 75%
Presentation Skills > 90%
Zoom & Arrows >80%
Knowledge >85%
Satisfaction >80%

 

I'm not at all dismissing the concern, in fact, here was my response...

First, and this is not sarcasm at all, thanks for taking the risk of being very open and direct. That is what it takes to help us figure out what is needed.

Second, you'll be happy to know that we are in the process of creating just what you are asking for, and much of it is already available.  I have a series of tutorails availalable here (see the side bar where you can find links to each or go to silverlight.net/learn and I'm in the process of writing Programming Silverlight for O'Reilly as part of my job for Microsoft!  We also have extensive documentation on the way in addition to what is currently available (remember, we're still in Beta).

Years ago my wife asked me why she received a report with a graph and the numbers it was based on. "Why do I need the graph if I have the numbers?" 

"Because," I said, "somewhere someone is asking their spouse 'why do I need the numbers if I have the graph?'"

Coming soon - better HDI Videos?

I'm 2/3  through Daniel Park's surprisingly excellent book Camtasia 5: The Definitive Guide and have found more than enough I didn't know and am glad to have learned to justify reading it.  I've also ripped through Timothy J. Koegel's The Exceptional Presenter...  so I'm geared to improve my videos (we'll see if they actually get better!)

The Exceptional Presenter: A Proven Formula to Open Up and Own the Room
by Timothy J. Koegel

Read more about this title...
Camtasia Studio 5: The Definitive Guide (Wordware Applications Library)
by Daniel Park

Read more about this title...

I have two more books on this theme on the way, and I'm quite eager to see what they have to offer:

Presentation Zen: Simple Ideas on Presentation Design and Delivery (Voices That Matter)
by Garr Reynolds

Read more about this title...
Beyond Bullet Points: Using Microsoft® Office PowerPoint® 2007 to Create Presentations That Inform, Motivate, and Inspire
by Cliff Atkinson

Read more about this title...

Who knows what nuggets these might yield?

Note, I've tagged these "Videos and Presentations" on my Library site and will tag some more as soon as I wake up.  If it turns out anyone has an interest, I'll create more tags for other relevant topics. For now, the books I think are among the best are tagged "required"

Thanks.

What do you think of my Silverlight How Do I Videos?

I'm always looking for ways to make this blog specifically and all my material on silverlight in general more interactive. Survey Monkey offers free surveys, so I thought I'd try it out by asking you to take a 1 page survey on what you think of my Silverlight 2 How Do I videos. If you have a moment you can take the survey here.

Also, don't forget that at the bottom of each video there is room for comments; your feedback is always welcome.

 

Thanks again.

In Silverlight, Tags are just strings...

[Updated with trivial, off-topic comment (at bottom of post) on 5/26]

Tim Binkley-Jones sent in a Tip of the Day that custom attached properties make a superior choice to Tags because, in Silverlight, Tags can only be strings.

This is not what I've been saying, but he is right; I was wrong.

He provides this excellent blog entry in which he explains the problem and the solution: custom attached properties.

ParthianShot

His Parthian Shot: "A custom attached property is the tool of a Silverlight/WPF developer.  Not as clumsy or random as a Tag, but an elegant tool for a more civilized technology."

Ouch.

 

 

 

 

 

 

--- Update 5/26 - Off point bit of personal trivia that explains the picture above --

When I was  a kid with few friends and no social skills, I used to make bizarre lists. Among them were brand names used as generics (yo-yo, fridge, xerox, jello, vaseline, scotch tape, kleenex, etc.) My favorite list was "phrases or words misused because the original is obscure but sounds like something common" I believe I had over 100 at one point

This latter list had on it

Original phrase Phrase it morphed into
Champing at the bit Chomping at the bit
On tenter hooks On tender hooks (interesting image)
Parthian shot Parting shot

Wikipedia: The Parthian shot was a military tactic employed by the Parthians, an ancient Iranian people. The Parthian archers, mounted on light horse, would feign retreat; then, while at a full gallop, turn their bodies back to shoot at the pursuing enemy. The maneuver required superb equestrian skills, since the rider's hands were occupied by his bow, leaving only pressure from his legs to guide his horse.

 

 

Converting it to VB

Just to tie the previous two blog posts together, I copied the C# into Instant VB and here is what it spit out (line break added to fit)

Private Sub AnyPropertyCheckBox_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    Dim isVisible As Nullable(Of Boolean) = Not AnyPropertyCheckBox.IsChecked
    For Each uie As UIElement In LayoutRoot.Children
        Dim cb As CheckBox = TryCast(uie, CheckBox)
        If cb IsNot Nothing Then
            If cb.Tag IsNot Nothing AndAlso cb.Tag.ToString().ToUpper() = "SEARCHCRITERIA" Then
                cb.Visibility = If(isVisible.GetValueOrDefault() = True, _
Visibility.Visible, Visibility.Collapsed) End If ' end if tag match End If ' end if check box Next uie ' end for each element End Sub ' end method

Blend, VS, Events and C#

From now until the summer I'll be working on videos, tutorials, presentations and blogging, but I'll also be writing Programming Silverlight 2 with Tim Heuer. Rather than convincing you that I'm continually hawking my book, I'd rather use the process of writing it as an opportunity to provide good, free, and I hope interesting material for this blog. (Write to me if I get the balance wrong!).

As an example, I ran into a bit of C# in what I'm writing in the first chapter that I thought made for an interesting example of how a Silverlight 2 programmer can? must? juggle the three principle technologies of (a) Visual Studio and (b) Blend and (c) a programming language of choice (which I can't quite understand why that wouldn't be C# or VB but I do know lots of folks disagree, and that in itself will make an interesting blog entry!)

So this blog entry may be of interest only for those of you who enjoy a bit of C#.

The context

This is early in the book and I'm laying out 9 checkboxes, used to designate search criteria. The first checkbox is "Any". If that is clicked the others are invisible,

AnyCheckBox

If Any is unchecked, all the other criteria appear,

AnyUnchecked

 

The book then goes on to show a number of things, including how to create the refining characteristics panels and how to overlay them, etc. etc. but the part I want to focus on here is a tiny detail: how you set the visibility flag on the check boxes. 

Here is the code I used.

private void AnyPropertyCheckBox_Click(object sender, RoutedEventArgs e)
{
    bool? isVisible = !AnyPropertyCheckBox.IsChecked;
    foreach (UIElement uie in LayoutRoot.Children)
    {
        CheckBox cb = uie as CheckBox;
        if (cb != null)
        {
            if (cb.Tag != null
                && cb.Tag.ToString().ToUpper() == "SEARCHCRITERIA")
            {
                cb.Visibility = isVisible == true ? 
                   Visibility.Visible : Visibility.Collapsed;
            }   // end if tag match
        }       // end if check box
    }           // end for each element
}               // end method

 

I'll walk through the entire method in just a second, but the key c# construct here is the use of the ternary operator (?:)

cb.Visibility = isVisible == true ? 
    Visibility.Visible : Visibility.Collapsed;

This operator (?:) is called ternary as it is the only operator that takes three parts. Here is how you read it (inside out).  First you evaluate the truth part  (isVisible==true).  This could have been written as

!AnyPropertyCheckBox.IsChecked == true

or

AnyPropertyCheckBox != IsChecked

To simplify I used an interim nullable boolean variable.

In any case, if the truth part evaluates true, then whatever is on the left side of the colon (in this case Visibility.Visible) is assigned as the result of the expression, otherwise, whatever is on the right side is assigned.

I admit, it is a construct only a former C programmer can love.

Note that the code I used  is exactly the same as writing

private void AnyPropertyCheckBox_Click(object sender, RoutedEventArgs e)
{
    bool? isVisible = !AnyPropertyCheckBox.IsChecked;
    foreach (UIElement uie in LayoutRoot.Children)
    {
        CheckBox cb = uie as CheckBox;
        if (cb != null)
        {
            if (cb.Tag != null
                && cb.Tag.ToString().ToUpper() == "SEARCHCRITERIA")
            {
               if ( isVisible == true )
               {
                   cb.Visibility = Visibility.Visible;
                }
                else
                {
                   cb.Visibility =  Visibility.Collapsed;
                }
            }   // end if tag match
        }       // end if check box
    }           // end for each element
}               // end method

 

So, as promised, here is the line by line walk through

// Declare isVisible to be a nullable boolean variable
// (it can have three values: true, false or null
// If AnyPropertyCheckBox's property IsChecked is true, assign false
// otherwise assign true.  This is dangerous code as the property could
// be null, and in retrospect I'd rewrite this as
// bool? isVisible = ! (AnyPropertyCheckBox.IsChecked == true);
// which would assign false if the property is true or null
bool? isVisible = !AnyPropertyCheckBox.IsChecked;

Next we iterate through all the children of LayoutRoot which is a grid that contains all the UIElements on the page

foreach (UIElement uie in LayoutRoot.Children)
{
     // code to explain here
}

Within that loop we'll grab each element and cast it to type Checkbox. The cast will either work or return null. If it does not return null, we'll ask the temporary check box if its tag is null. If not, then we have a check box with a tag and we can see if that tag, when turned to a string matches the tag we're looking for

// try casting to a checkBox
CheckBox cb = uie as CheckBox;

// if the cast is not null, it really was a check box
if (cb != null)
{
    // see if the tag is null and if not if the tag as a string
    // matches what we're looking for
    if (cb.Tag != null
        && cb.Tag.ToString().ToUpper() == "SEARCHCRITERIA")
    {
        // code here
    }   
}       

Note that the test for the tag not being null and then turning the tag into a string is accomplished in a single if statement. That is safe if you get the order right and use the && symbol between the two expressions, because they will short circuit. That is, because both must be true, if the first is false, the second will never evaluate (which is a good thing, because if the first is false, then the Tag is null and trying to call ToString on it would throw an exception).

Finally, inside the if statement is the ternary operator where we set the visibility.

Not bad, but not obvious if you're not comfortable with a bit of C#.

Posted by jesseliberty | 8 comment(s)
Filed under:

My new favorite utility for .NET

Before I say a word, let me tell you that Dave from Tangible Software has been sending me free copies of InstantVB and Instant C# for years and they posted a testimonial from me on their site. That is my only involvement with them, but there you have it.

Now, don't let Dave know, but while I've been meaning to use  this software for a long time, I hadn't recently, because every project that I thought would be bi-lingual wasn't. Until recently, when I switched over to writing my tutorials and videos in VB, and I wanted to be able to grab something I'd written in C# and get its equivalent in VB.

Yow! this program is easy, accurate and blazingly fast (25K lines/minute)

InstantVB

I really want to ship a copy with every book I write so that folks can stop worrying about which language the book is written in.  This is not freeware (its note even all that inexpensive) but it is amazing (they state that on our 101 C# samples they convert 99.98% without adjustment!)  and it is making my life a whole lot easier.

I'll be interested to hear from VB programmers in coming weeks if they read any of my code and have the experience of "yes, that is technically correct code, but no VB programmer would ever write it like that."

Net Net: look forward to more of my work in both C# and VB.

-j

Expression Blend for Programmers

I have set out on an integrated set of videos, tutorials and blog posts on the subject of using Expression Blend from the point of view of Silverlight 2 Programmers.  To get things going, I created a 3 part video series based on ScottGu's extended blog tutorial and I have a tutorial on the topic due to publish early next week.

I am now in the process of creating more videos in which I will be exploring how Blend can make certain tasks far easier for the Silverlight programmer; keep an eye out for my video on Blend and Data binding.

I will express a certain resistance to starting this, and I've been trying to figure out why. Part of it is that I'm very comfortable in Visual Studio and much of it is that nearly all the books on Blend are targeted at Designers rather than at Programmers. It is my goal to overcome those concerns for developers who share these concerns, and to integrate Blend into my toolset; using Blend for its strengths, and Visual Studio where it is stronger, and, eventually, to think of them as two faces of a single semi-integrated tool.

I'm not sure what will happen when Visual Studio's design surface is fully read/write. I think by then I'll be so comfortable using Blend's features that I'll continue to do so for some tasks. I'd be interested in your experiences as well.

Posted by jesseliberty | 12 comment(s)
Filed under:
Next