|
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, If Any is unchecked, all the other criteria appear, 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...
|