DCSIMG
June 2009 - Posts - Alex Golesh's Blog About Silverlight Development

June 2009 - Posts

Quick Tip: LINQ & Data Binding notifications

In Silverlight & WPF we could databind to the LINQ query results:

private ObservableCollection<string> someData = new ObservableCollection<string>();

//Somewhere in code
someData.Add("Alex");
someData.Add("Alen");
someData.Add("Josh");
someData.Add("Brad");
var res = from data in someData
           where data.StartsWith("A")
           select data;

listbox.ItemsSource = res;

”listbox” is the name of the Listbox on my XAML page.

When application will load we will get expected results:

image

But what happens when out collection (reminder: ObservableCollection, which implements INotifyCollectionChanged) changed?

someData.Add("Antony");

Nothing! Because we bounded to the LINQ query (predicate), and the query was executed while databinding occurred :) LINQ query does not fires any notifications because it is not re-evaluated on collection change, but on usage of the predicate.

Now the quick workaround:

Rebind once again to the same predicate (on collection change event), and it have you UI updated:

someData.CollectionChanged += (s, e) =>
  {
      listbox.ItemsSource = null;
      listbox.ItemsSource = res;
  };
image

 

Enjoy,

Alex

Silverlight 3 Quick Tip #10: Styling Improvements

Silverlight 3 bring long-awaited improvements in styling mechanism: “BasedOn” mechanism, Merged Resource Dictionaries and eliminates “write once” style setting behavior. Let’s see those features.

BasedOn

Styles can be “derived” from one another. Perfect for cascading/inheriting styles.

Let’s define style for a… Button (well, in demos it is always a Button, TextBox, etc. ;))

<Style x:Key="BaseButtonStyle" TargetType="ButtonBase">
     <Setter Property="Width" Value="100"/>
     <Setter Property="Height" Value="25"/>
     <Setter Property="Margin" Value="5"/>
</Style>

To “derive” from existing style we should specify BasedOn property

<Style x:Key="DerivedButtonStyle" TargetType="ButtonBase" BasedOn="{StaticResource BaseButtonStyle}">
      <Setter Property="Background" Value="Red"/>
      <Setter Property="BorderBrush" Value="Blue"/>
      <Setter Property="BorderThickness" Value="3"/>
</Style>

The new style will have 6 properties set. Also we will be able to “derive” from style and “override” some of setters:

<Style x:Key="ExtendedButtonStyle" TargetType="ButtonBase" BasedOn="{StaticResource DerivedButtonStyle}">
     <Setter Property="FontFamily" Value="Trebuchet MS"/>
     <Setter Property="FontSize" Value="20"/>
     <Setter Property="Height" Value="35"/>
     <Setter Property="Width" Value="150"/>
     <Setter Property="Background" Value="Green"/>
</Style>

All those styles could reside in ResourceDictionary. This was the feature of Silverlight 2. Silverlight 3 adds to it ability to create MergedResourceDictionary. Merged Resource Dictionaries will use separate Resource Dictionary files in order to create a Merged Resource Dictionary. Resource Dictionary files could be the part of current assembly (resource) or part of referenced external assemblies. Also it could have style definitions exactly like standard Resource Dictionary

<ResourceDictionary>
   <ResourceDictionary.MergedDictionaries>
      <ResourceDictionary>
         <SolidColorBrush Color="Aqua" x:Key="My_AquaColor"/>
         <Style x:Key="RectangeStyle" TargetType="Rectangle">
            <Setter Property="Stroke" Value="Black"/>
            <Setter Property="StrokeThickness" Value="0.5"/>
            <Setter Property="Margin" Value="5"/>
            <Setter Property="Width" Value="20"/>
            <Setter Property="Height" Value="20"/>
         </Style>
      </ResourceDictionary>
      <ResourceDictionary Source="/Resources/colors.xaml"> <!—Assembly resource-->
      <ResourceDictionary.MergedDictionaries>
         <ResourceDictionary>
            <SolidColorBrush Color="GreenYellow" x:Key="My_GreenYellowColor"/>
         </ResourceDictionary>
       </ResourceDictionary.MergedDictionaries>
     </ResourceDictionary>
     <ResourceDictionary Source="/Resources;component/resources.xaml"/> <!—External assembly resource-->
   </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

Last, but not least, Silverlight 3 applications now support resetting styles as many times as needed:

Style style = this.Resources["DerivedButtonStyle"] as Style;

if (null != style)
   btnBase.Style = style;

 

More to come - stay tuned!

 

Enjoy,

Alex

Silverlight 3 Quick Tip #9: DataBinding with Validation

Silverlight 3 provides validation mechanism while using Two-Way data binding.

Silverlight 3 also provides default a Validation Exception UI – callout with exception details, which could be customized.

Many input-related controls such as TextBox, CheckBox, etc. have built-in support for validation.

How to use? Simple, like everything with Silverlight: To enable validation, use the ValidatesOnExceptions property.

<TextBox Text="{Binding ID, Mode=TwoWay, ValidatesOnExceptions=True}" />

//Code behind – property definition
public string ID { get { return id; } set { if (string.IsNullOrEmpty(value)) throw new Exception("This field can't be empty!"); id = value; } }
image 

Example on ListBox:

<ListBox SelectedItem="{Binding Score,Mode=TwoWay,ValidatesOnExceptions=True}">
                    <
sys:String>Best</sys:String>
                    <
sys:String>Good</sys:String>
                    <
sys:String>Ok</sys:String>
                    <
sys:String>Acceptable</sys:String>
                    <
sys:String>Bad</sys:String>
</
ListBox>

//Code behind  property definition

public string Score
        {
            get { return score; }
            set
            {
                string[] acceptable = new string[] { "Ok", "Best", "Good" };

                if (!acceptable.Contains(value))
                    throw new Exception("The '" + value + "' is unacceptable");
                else if (value == "Ok")
                    throw new Exception("Ok is not the expected answer");

                score = value;
            }
        }

Sample UI:

image

Enjoy,

Alex

Silverlight 3 Quick Tip #8: Caret Brush

I love an ability to change the standard look and feel of the controls in Silverlight. I like “dark” themes for my applications :)

While working with Silverlight 2, many times I’ve found myself with very strange UX – my very nice black themed application with white texts confuses users…

image

Where is the caret in this text box? What if user want to fix something, how does he/she knows where to type…

One of nice additions in Silverlight 3 was an ability to change the color of the TextBox Caret. Now TextBox exposes “CaretBrush” from Brush type, which gives an ability to use any Brush within. Previous strange UX (with default black caret) now solved – white caret is much better here:

image

But the CaretBrush is a brush! It could be anything, which fits the Brush definition… It could be gradient, picture or even video!!!

Gradient brush? No problem:

image

Image Brush? Sure:

image

How it works? Well, this part is actually very simple:

<TextBox Background="Black" Foreground="White" Text="White text, black background and White caret" CaretBrush="White"/>

Gradient brush:

<TextBox Background="Black" Foreground="White" Text="White text on black background with gradient caret" >
            <TextBox.CaretBrush>
                <LinearGradientBrush StartPoint="0,0" EndPoint="0,1" >
                    <GradientStop Color="Red" Offset="0.0"/>
                    <GradientStop Color="Orange" Offset="0.143"/>
                    <GradientStop Color="Yellow" Offset="0.286"/>
                    <GradientStop Color="Green" Offset="0.428"/>
                    <GradientStop Color="LightBlue" Offset="0.571"/>
                    <GradientStop Color="Blue" Offset="0.714"/>
                    <GradientStop Color="Violet" Offset="0.857"/> 
                </LinearGradientBrush>
            </TextBox.CaretBrush>
        </TextBox>

and Image brush:

<TextBox Width="150" Text="Text &amp; picture caret" >
            <TextBox.CaretBrush>
                <ImageBrush ImageSource="/CaretImage.jpg" />
            </TextBox.CaretBrush>
</TextBox>

 

Easy, huh?

 

Enjoy,

Alex

Silverlight 2 applications: a day after Silverlight 3 release

Silverlight 3 release date is approaching, and I’m getting questions what will happen to existing Silverlight 2 applications after it will be released. Also I’m getting questions about the runtime version upgrade.

Let’s see what will happen after Silverlight 3 will be released…

Those who already using Silverlight 2 and getting automatic updates will receive the new runtime automatically. Everyone else need to download and install it manually.

The updated clients will be able to run Silverlight 2 applications as it was before the runtime update. It is possible because of “quirk mode change” – the special mode, that will not enforce Silverlight 3 runtime/features if the runtime detects that the application being run was designed for Silverlight 2. In this way, Silverlight 3 is made “bug compatible” with Silverlight 2 when a Silverlight 2 application is being run (i.e. all bugs from original Silverlight 2 will occur, even if Silverlight 3 already fix them). This will happen until the developers will not compile the application with Silverlight 3 runtime.

Actually, the detection made by querying the “RuntimeVersion” attribute in AppManifest.xml: “RuntimeVersion” reflects the build of Silverlight that was on the developer’s machine when the application was compiled. Thus, if Silvelright 3 runtime will detect for example RuntimeVersion="2.0.31005.0" (Silverlight 2 RTW version) it will execute the application in “quirk mode”, if “RuntimeVersion” will be Silverlight 3 version the application will work in full Silverlight 3 mode.

Now the quick tip for those, who developed Silverlight 2 application:

While updating Silverlight 2 application to use version 3 make sure that you also update update the new “minRuntimeVersion” attribute to the Silverlight 3 ones to ensure the end-user has the correct version.

 

Stay tuned for more updates/tips

Alex

What’s new in Silverlight 3 and Expression Blend 3 – DevDay (22 July 2009)

Silverlight 3 will be released very soon. Silverlight Logo

Many new features were added, many improvements were made. Come and see me presenting what’s new in Silverlight 3 and Expression Blend 3 at Microsoft Israel Offices, 22 July 2009.

I will talk about new features, new and improved technologies.

Will see Silverlight 3 tools and features in current version of Visual Studio 2008 and in upcoming release of Visual Studio 2010 (Beta). Will see what’s new in Expression Blend 3.

Many cool demos, tips & tricks are promised!!! :)

Details and Registration

 

See you there,

Alex