Archive for the ‘Silverlight’ Category

A Few Good Metadata Options for Silverlight

Saturday, May 8th, 2010

I’d like to highlight one more feature that is available in Silverlight if you use my code snippets.

Those who watched the value coercion video might have glimpsed the following enum within the FrameworkPropertyMetadata.cs code file:

[Flags]
public enum FrameworkPropertyMetadataOptions : int
{
    None = 0x0,
    AffectsMeasure = 0x1,
    AffectsArrange = 0x2,
    AffectsParentMeasure = 0x4,
    AffectsParentArrange = 0x8,
}

This enum provides a limited subset of the metadata options that are available in WPF.  Specifically, these are the options used with dependency properties that affect layout.

How do metadata options work?

If you are not familiar with these metadata options, here’s a quick rundown…  In WPF, a dependency property on a framework element can be registered with one or more metadata options.  This is done by combining the desired flags using a bitwise “OR” and then passing that value into the appropriate DependencyProperty.Register() overload.

As an example, the Width property on FrameworkElement is registered with the AffectsMeasure option.  As such, the property engine will take care of invalidating measure on the target element whenever the Width property changes.

The other layout options work pretty much the same way.  The AffectsArrange flag will cause InvalidateArrange() to be called on the target element when the property changes.  The AffectsParentMeasure and AffectsParentArrange flags will cause InvalidateMeasure() and InvalidateArrange() to be called, respectively, on the target element’s parent.

It’s All About Portability

In Silverlight, there is no native mechanism for registering a property to affect measure or arrange.  As such, you typically register a PropertyChangedCallback on the property and then explicitly call InvalidateMeasure() and/or InvalidateArrange() within your callback. 

If you use my snippets, you can follow the exact same approach in Silverlight that you would use in WPF for properties that affect layout. My FrameworkPropertyMetadata class will take care of the necessary layout invalidations.  So a property that affects measure could be declared in Silverlight using my ‘dp s1’ snippet, as follows:

#region VerticalExtent

/// <summary>
/// VerticalExtent Dependency Property
/// </summary>
public static readonly DependencyProperty VerticalExtentProperty =
    DependencyProperty.Register("VerticalExtent", typeof(double), typeof(MyControl),
        new FrameworkPropertyMetadata(double.NaN,
            FrameworkPropertyMetadataOptions.AffectsMeasure));

/// <summary>
/// Gets or sets the VerticalExtent property. This dependency property
/// indicates the vertical extent of the control.
/// </summary>
public double VerticalExtent
{
    get { return (double)GetValue(VerticalExtentProperty); }
    set { SetValue(VerticalExtentProperty, value); }
}

#endregion

What about the other WPF metadata options?

There are several metadata options in WPF that are not included in my Silverlight enum.  These are intentionally excluded because they either cannot be supported outside the native Silverlight framework (e.g., the property engine would need to be modified to support the NotDataBindable option) or they simply don’t make sense in Silverlight (e.g., Silverlight does not currently support direct rendering via an OnRender() override, so I don’t provide an AffectsRender flag).

I hope you find the provided layout metadata options handy!

Cheers!
Dr. WPF

Updated Code Snippets for WPF and Silverlight

Friday, April 30th, 2010

I originally posted my Visual Studio WPF code snippets back in November of 2007. At that time, I was actually on the road delivering training for Silverlight 1.0. My co-instructor observed me using the snippets and suggested that I make them publicly available. It turned out to be a good suggestion, as I’ve received great feedback on the snippets over the last few years. Hopefully they’ve helped a few of you gain some productivity too. 🙂

We’ve definitely come a long ways since the days of SL 1.0 and javascript! My snippets have evolved over the years to better meet the needs of both WPF and Silverlight. An update is long overdue, so I’ve now posted the latest version of my snippets online…

 

Download the Snippets Here

 

Pick Your Language

As before, the installer package contains both C# and VB versions of each snippet. If you double click the .vsi file, you can choose exactly which snippets to install.

For those of you working in C#, you only have to remember a handful of shortcuts to access any of the 86 unique snippets:

  • dp (for dependency properties)
  • inpc (for an implementation of INotifyPropertyChanged)
  • op (for observable properties)
  • rc (for routed commands)
  • re (for routed events)

For those of you who work in VB, well… you have my sympathies! Just kidding. 😉 I would suggest using the snippet picker until you learn the shortcuts for the particular snippets that you find most helpful.

Pick Your Framework

Although my (self-endowed) doctoral degree is in WPF, I also spend a good amount of time writing Silverlight code. This latest snippet package brings my Silverlight snippets in line with my WPF snippets. For example, all 6 variations of dependency property declarations are now fully supported for SL 3 and SL 4. In C#, you can quickly access the dependency property snippets for Silverlight by typing ‘dp’, hitting Tab twice, and then typing ‘s’. You should see something like the following:

Silverlight Snippets

In addition to declaring DPs, I also use the ‘inpc’ and ‘op’ snippets quite heavily in Silverlight.

The ‘rc’ and ‘re’ (routed commands and routed events) snippets are mostly for WPF. However, the ‘re c’ snippets are very useful for declaring custom event args even in Silverlight. Just remember to hit delete when you tab to the “Routed” field in the snippet. There is also an ‘re s’ snippet that I use in Silverlight when I need to provide a property changed event. Note that the event it provides is not truly routed, as SL does not allow you to insert custom events into its routed pipeline. Still, it is often the appropriate choice when you want to create cross-framework code.

What changed?

Aside from the addition of about 20 new snippets, there were also a few improvements to the older snippets.  If you are using an earlier release, you may notice a few of these changes.  Probably the biggest difference is in the following method signature (found in many DP snippets):

Old Snippet

/// <summary>
/// Provides derived classes an opportunity to handle changes
/// to the Whatever property.
/// </summary>
protected virtual void OnWhateverChanged(DependencyPropertyChangedEventArgs e)
{
}

New and Improved Snippet

/// <summary>
/// Provides derived classes an opportunity to handle changes 
/// to the Whatever property.
/// </summary>
protected virtual void OnWhateverChanged(double oldValue, double newValue)
{
}

Without going into the mundane details, I’ll just say that the motivation for changing this signature on the WPF snippets was mostly code portability between WPF and Silverlight.  The former signature did not always work well because Silverlight does not provide a public constructor for DependencyPropertyChangedEventArgs.  This became problematic in coercion scenarios.  I also prefer the latter version because it provides a type-specific OnChanged callback, but that’s just a personal preference.

Are the old snippets still available?

For the luddites who are not ready for these modernized snippets, you can still download the older snippets here. 😉

For everyone else, I hope you like the new snippets!  There are a few gems in there which I’ll expound upon further in future posts.

Silverlight: How I Really Feel About the Iridescent Thong

Saturday, March 21st, 2009

First, I have to give huge props to Microsoft for throwing an excellent party in Vegas this past week!  The week was definitely packed with excitement and backed by great content.  Be sure to check out the recorded sessions if you were not able to attend Mix09.

This post represents my response to this year’s big unverbalized question…

What about WPF?

Yes, this year’s conference felt like it was all about Silverlight 3.  I think Microsoft would readily acknowledge that this was by design (no pun intended).  And this was actually fine with me, since the Silverlight platform has made such great strides over the past couple of years.  It certainly deserves the attention it is now getting.

I have a reputation for making fun of Silverlight from time to time.  Truth be told, I bare no ill will toward Silverlight at all.  I’ve even delivered Silverlight training on several occasions.  I think of her as a kid sister to WPF (which plays the role of big sister, in case you were curious about either platform’s gender).  Privately I’m pulling for Silverlight to make good, but that doesn’t stop me from publicly taking shots at her whenever the opportunity arises.  It’s all in good fun… really!  🙂

I’m not exactly sure what role I’d give myself in all of this.  Some might say that WPF and I are BFFs, but I’d argue against the latter F.  To me, "forever" is a word that has no place in technology.  When it comes to WPF, my devotion only goes as far as the platform presently supports.  I am her student; I am her practitioner; I am even her disciple; but make no mistake… if something better comes along, I will turn her out like a two-bit whor… rible analogy!  Let me change directions…

Based on what I see on the horizon right now, I think WPF and I still have a bright future together.  Silverlight gets more impressive with each release, but it has quite a ways to go before it reaches parity with WPF.  I just spent the better part of a conference watching web developers "ooh" and "ah" over features that I’ve been using in WPF for years now.  (Imagine how they’d feel if they had something as basic as a trigger!  See… there I go again…  I just can’t help myself. ;))

Additionally, I’m a platform guy.  So much of what I do now requires a full trust environment with access to platform APIs.  Until Silverlight breaks out of the sandbox and allows me to harness platform-specific features (which is not likely in the near-term, since it is so focused on cross-platform reach and a small footprint), I think WPF and I will stay pretty tight.

Why bring all this up now? 

I’ve received a number of… shall we say… "concerned" inquiries lately about the shrewdness of adopting WPF for new or future projects while Microsoft has such an obvious slant toward Silverlight. 

My honest recommendation to anyone deciding between WPF and Silverlight is unchanged over the last couple of years.  The platform has to be chosen based solely on the project requirements.  If Silverlight meets the requirements of your project and you need cross-platform reach, then you should definitely target Silverlight.  End of story.

On the other hand, if you’re developing a full trust, Windows application, you will likely be far more successful with the more mature (and in my humble opinion, more elegant) big sister, WPF.

Impending Doom

Some emails have expressed an explicit fear that WPF is about to be abandoned by Microsoft and then disappear completely.  Let me put my response to such concerns in terms that only a geek can truly appreciate… 

Don’t Panic!

To allay your fears, let me point you toward two very big buoys floating in the waters around Redmond: Expression Blend and Visual Studio 2010.  The user interfaces these products are actively being built in WPF.  Blend always has been a WPF application.  For information on the upcoming Visual Studio 2010 UI, check out Jason Zander’s blog.  Feel free to anchor yourselves to these buoys.  If these projects change direction, make sure you follow!  (Can you imagine a Visual Studio user interface written in Silverlight?  Even I think that would be awesome!)

I would also point out that many new features highlighted at Mix09 actually represent nice WPF advances too.  I know Silverlight received most of the glory, but new Blend 3 features like Sketch Flow, Behaviors, and the new Adobe importers are actually just as pertinent to WPF as they are to Silverlight.  And of course, there was the sneak peak at WPF 4.

The Big "If"

So what happens down the road "if" Silverlight does reach parity with WPF and it finally breaks out of the sandbox? 

Should that ever happen, my response to potentially losing WPF would basically be a shrug and a big, "So what?"  If Silverlight v.Next++ gives me everything I need for Windows client development and supports the same collaborative workflow as WPF, then why would I (or anyone) mourn the loss of WPF?  At that point, I’d be more concerned if WPF *was* still around.

Again, let me be clear…  I think this latter scenario is a big "If" and should things go in that direction, I don’t think we’re talking near-term.  Microsoft can move very fast when the correct motivations are in place, but even at full speed, I think this would be a multi-year scenario.

Again, my take is that nothing lasts forever in technology.  Both WPF and Silverlight will eventually be replaced by something bigger and better… or maybe smaller and better… who knows?  For now, I’m a WPF junkie and a Silverlight user.

Now the Important Stuff…

Here are the Sudoku puzzles I conquered on my return flight from Vegas: One, Two, and Three. (See JAGS 10K Instructions for mouse play.) 

Yep, three of them!  Usually, I only make it through a single puzzle, but I was unexpectedly bumped to first class on this flight where I basqued in the glory of geek icons such as Scorbs, The Gu, the WPF Wonder Man, and even Nate Dunlap!  Their collective auras must have increased my puzzle IQ.

The BIG Problem with Silverlight's Control Templating Model

Monday, March 24th, 2008

Robby has just fired this shot in The Great Templating War Debate of 2008.  I don’t often disagree with Robby on platform issues, but…  I am now compelled to reply with an opposing viewpoint on this issue.

In my opinion, there are several problems with the templating model in Silverlight 2.0. I’m not going to focus on some of the more obvious ones (like the fact that WPF and Silverlight are using completely different models) because I think they have been covered quite well by others.

Instead, I’m going to focus on what I consider to be the BIG problem… Silverlight’s templating model breaks the developer/designer workflow.

The biggest value proposition for both Silverlight and WPF is the workflow that they enable between developers and designers. As a left-brained developer, you definitely do not want me involved in an application’s UI design. (Trust me on that!)  The good news is that in WPF, you don’t need to worry.  I can focus on the application’s functionality and the design work can be handled by a truly capable UX designer.

You may reasonably be wondering, "What does application development and design have to do with control development and design?"  Control development in WPF is very much just a microcosm of application development in WPF. I tend to write my application objects (user controls, windows, pages, the application itself) in the exact same manner as custom controls. This enables designers to create a UI that simply reflects the state of the application objects. If you think about it, this is a little M-V-VM pattern built right into WPF’s control and application models.

To fully appreciate the workflow that this model enables for both designers and developers, you just need to experience it once… You turn over a really drab, form-looking UI to your designer and watch what they do with it… Wow!  It’s an amazing feeling just to think that you had some part in the creation of such a thing of beauty! 

Perhaps you think this is just hyperbole.  Well, I know I’m not the only developer who feels this way!  And you, too, can feel this exuberance enabled by the developer/designer workflow.  Simply download Podder and toggle between Josh’s skin and Grant’s skin!  (Sorry Josh. :P)

Back to the issue at hand…  I happen to be very good at analyzing a control to determine the states that it will need to support. I’m also quite adept at implementing the functionality of a control and making sure that the functionality is exposed via the necessary methods and commands. Moreover, I’m very passionate about this type of control development.  I think the designers I work with will validate that I always strive to provide them with all the hooks they could possibly want when it comes to styling and templating my controls.

The term that WPF uses for this control model is "lookless". It basically means that the code for a control (or application) is written in a manner that makes no assumptions about the presentation layer. The control simply exposes state information via properties and events along with execution entry points via methods and commands.

Silverlight’s templating model completely breaks this lookless control model. It requires that the developer meddle in areas where they don’t belong (such as looking for and executing storyboards in the UI layer). Furthermore, it takes away the ability of designers to think outside the box when they define UX interactions because they must conform to whatever hooks have been provided by (a.k.a., hardcoded into) the control.  Or worse, it encourages designers to actually meddle in the control’s code where they don’t belong.

Without the lookless model, you cannot achieve what Nathan describes as the "holy grail" for developer/designer workflow. I completely agree. (Nathan’s blog, by the way, is another excellent resource for anyone who would like a designer’s view of the WPF and Silverlight platforms.)

The process of creating great controls will always involve designers and developers working together to meet each other’s needs. However, they each have their own strengths. As a developer, I DON’T WANT TO THINK ABOUT DESIGN!

The reason I am so passionate about the WPF platform is that it frees me to do what I do best… write code. At the same time, it frees designers to do what they do best… create compelling user experiences by designing the look and feel of an application and its controls. This is all enabled by WPF’s styling and templating model.

The arguments I keep hearing for the decisions being made with respect to Silverlight’s templating model all seem to revolve around toolability. Namely, applications like Blend need a more intuitive way to support styling and templating.

My stance is that the architecture of the platform should not be driven by the needs of the tools. The platform should definitely accomodate those needs, but this can be done through helper classes. The platform’s architecture needs to be driven by decisions that best enable the next generation of killer software experiences. I fully believe these experiences can best be enabled using a truly lookless model. I also fully believe that this model enables the most ideal workflow between developers and designers.

So how can Silverlight fix this?

Simple. Give us property triggers, data triggers, and event triggers in both styles and templates.