Architect or Cobbler?
Good code starts with good design

Style

Sunday, November 19, 2006

I've already blogged about style earlier in my blog, but styles are absolutely essential to the success of any Xaml app, particularly when you have many controls that share behaviour.  In the PenWidthDialog we've got two text boxes that we want to style the same.  I'd like their background to turn red, and a tooltip to appear with the error message returned from the ValidatorRule.  To do this you need to add a Resources section to the Xaml, give your style a key. like this:

 <Window.Resources>
    <Style x:Key="MyTextBoxStyle" TargetType="{x:Type TextBox}">
      <Style.Triggers>
        <Trigger Property="Validation.HasError" Value="true">
          <Setter Property="ToolTip"
            Value="{Binding RelativeSource={RelativeSource Self},
          Path=(Validation.Errors)[0].ErrorContent}"/>
          <Setter Property="Background" Value="Red" />
        </Trigger>
      </Style.Triggers>
    </Style>
  </Window.Resources>

This probably needs a little bit of explaining.  The style has to know the types which it can be applied to , and the Triggers collection is a collection that contains Triggers.  Triggers are objects which are activated in response to either a property changing or an event being fired.  In our case the Trigger is fired when the property Validation.HasError changes to true.  At that time two properties of the TextBox are changed - the Tooltip property is set so that it displays the first error message in the Validation.Errors collection and the Background is set to red.  The RelativeSource property allows you to specify a source for the binding, instead of walking the control tree.

Now all you have to do is apply these styles to your textbox, and when you get a validation error, then it will look something like this:

We're nearly done.  All we have to do is sort out the printing, and saving and restoring the state.  I'm sure I'll get a chance next week to finish this off.


# posted by James @ 6:00 PM   0 comments Comments: Post a Comment

<< Main blog page
This page is powered by Blogger. Isn't yours?