Blend for Visual Studio 2012 by Example: Beginner’s Guide Discount Offer

I recently published a review of Pack Publishing’s new book, Blend for Visual Studio 2012 by Example – Beginner’s Guide. Well, guess what, Pack is offering a 50% off discount if you buy it between 17th and 25th of September! You just need to use this discount code:

Banner

Keep in mind that this code is only valid for this ebook!

So, what are you waiting for? Winking smile

Blend for Visual Studio 2012 by Example Review

Introduction

I was recently asked by Packt Publishing to review another of their books. This time it was Blend for Visual Studio 2012 by Example, a book by Abhishek Shukla (@abbeyshukla), apparently, the first book on Blend for Visual Studio, even if it still covers Visual Studio 2012, most of it will apply to 2013 as well. My interest in Blend came from the fact that I recently had to work with Silverlight, and Blend is, of course, one of the must-have tools.

This book is for beginners on Blend, and it covers a number of technologies around XAML:

  • Windows Presentation Foundation (WPF)
  • Silverlight
  • Windows Phone
  • Windows Store

Each chapter starts by explaining some concept and then goes on to a sample application that demonstrates it.

Chapter 1 – Getting Started with Blend

So, the first chapter is just an introduction on what Blend is used for, how to get it and install it, the Blend IDE, etc. We are guided through a sample (and simple) application built in Silverlight. I’d say it’s a decent start.

Chapter 2 – Layout Panels

The second chapter talks about one of the fundamental building blocks in any graphical application: the layout components. We are presented the five basic layout panels existing in WPF (Grid, Canvas, Stack Panel, Wrap Panel and Dock Panel) and given one example of its usage (except Wrap Panel and Dock Panel). Others, like Border, Popup, Scroll Viewer, Uniform Grid and View Box are also just succinctly described.

Chapter 3 – Working with XAML

This one is about the Extensible Markup Language (XAML), the glue that brings together WPF, Silverlight, Windows Phone and Windows Store apps. We are taught about namespaces and custom registrations, the XAML syntax, and how XAML relates to C#. We also learn about styles, a very important concept.

Chapter 4 – Styles and Templates

In this chapter, we have more styles and also templates and resources, three concepts closely intermingled. We learn about the several levels on which resources can be declared and the difference between static and dynamic resource references. Then, style definitions, targeting and inheritance and how to use resource dictionaries to skin our applications. Templates come next, in its two major flavors (control and data). We see how we can edit the templates of existing controls

Chapter 5 – Behaviors and States in Blend

This time its all about adding interactivity to applications, through behaviors and visual states. We learn about Blend’s own behavior library, that can be used for both WPF and Silverlight, and get to create a sample animation. Next come visual states, the default XAML mechanism that is supported natively by both Silverlight and XAML, and we also learn how to do a similar animation effect.

Chapter 6 – Understanding Animation and Storyboards

In chapter 6 we go more deeply into animations using the IDE’s powerful storyboard tools. We learn how to record, edit and play an animation built exclusively using these tools and how it gets translated to XAML.

Chapter 7 – Understanding Databinding

Another of the major concepts in XAML is databinding, the subject for this next chapter. We are taught about dependency and attached properties, databinding modes and directions, how to load data from either XML files or our own classes and to bind it to controls. One thing that I think should be here is value converters.

Chapter 8 – Vector Graphics

This chapter talks about the graphic shapes of XAML. We learn how to import existing vector files into XAML and how to create custom shapes.

Chapter 9 – User Controls and Custom Controls

Another hot topic is reusable controls, of the two basic types: user controls and custom controls. We learn about the difference between the two, what they are used for, and create one sample of each.

Chapter 10 – Creating Windows Phone Apps

This chapter is totally dedicated to building Windows Phone 8 apps. It explains the different types of projects, device sizes and resolutions and introduces the Windows Phone Emulator. Then it talks about the requirements that need to be met in order to submit an app to the Windows Store, and how can we test its compliance. Note that only the user interface is covered, not more advanced features of Windows Phone, like sensors, etc.

Chapter 11 – Creating Windows 8 Store Apps

The final chapter is about building Windows Store Apps. We learn about the different kinds of apps available, how to certify and submit our app to the store.

Conclusion

Like I said, it is a book for beginners, without any knowledge of XAML, and from this perspective, I think it does a decent job. It wouldn’t be possible to cover everything , but some important topics received a fair treatment.

Adding Custom Validation Messages in Silverlight

Sometimes it is useful to add our own validation messages to a Silverlight control, normally because we are doing custom validation through code, not through the reguar IDataErrorInfo, INotifyDataErrorInfo or ValidationAttributes. This is not straightforward, but it is possible. An example might be:

//this class is used for throwing an exception upon binding

//has to be public, doesn't need to implement any interfaces

public class TagModelError

{

    private readonly String errorMessage;

 

    public TagModelError(String errorMessage)

    {

        this.errorMessage = errorMessage;

    }

 

    public Object Tag

    {

        get

        {

            return new Object();

        }

        set

        {

            throw new ValidationException(this.errorMessage);

        }

    }

}

 

//extension method for adding validation messages on a control

public static void AddValidationError(this Control control, String errorMessage)

{

    var expression = elm.GetBindingExpression(FrameworkElement.TagProperty);

 

    if (expression == null)

    {

        expression = control.SetBinding(FrameworkElement.TagProperty, new Binding("Tag")

        {                

            Mode = BindingMode.TwoWay,

            ValidatesOnExceptions = true,

            UpdateSourceTrigger = UpdateSourceTrigger.Explicit,

            Source = new TagModelError(errorMessage)

        }) as BindingExpression;

    }

 

    expression.UpdateSource();

}

In this example I am using the TagProperty, because it is seldom used, but you can use whatever you like. The trick here is to force the update of a bound object, which throws an exception, which in turn is propagated as a validation error.

Silverlight Transform Markup Extension

<ComboBox ItemsSource="{Binding ItemsSource, ElementName=MyDataSource}, Converter={StaticResource MyConverter}}" Width="100" Height="30"/>

<ComboBox ItemsSource="{Binding ItemsSource, ElementName=MyDataSource}, Converter={StaticResource MyConverter}}" Width="100" Height="30"/>

Did you ever have one of those situations where you need to apply a data source to a control, but also convert the each of the data source elements?

Normally we set the data source to the DataContext or ItemsSource property and add an item template where we specify the converter, but sometimes this can’t be done this way, for one reason or the other. So, I worked out a simple solution: the TransformedItemSource! What it does is, it allows us to specify a converter for each of the source values in the data source collection, not the data source as a whole.

Here it is:

public class TransformedItemSource : DependencyObject, IEnumerable

{

    public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(TransformedItemSource), new PropertyMetadata(null));

    public static readonly DependencyProperty ConverterProperty = DependencyProperty.Register("Converter", typeof(IValueConverter), typeof(TransformedItemSource), new PropertyMetadata(null));

    public static readonly DependencyProperty ParameterProperty = DependencyProperty.Register("Parameter", typeof(Object), typeof(TransformedItemSource), new PropertyMetadata(null));

    public static readonly DependencyProperty CultureProperty = DependencyProperty.Register("Culture", typeof(CultureInfo), typeof(TransformedItemSource), new PropertyMetadata(CultureInfo.CurrentCulture));

    public static readonly DependencyProperty TargetTypeProperty = DependencyProperty.Register("TargetType", typeof(Type), typeof(TransformedItemSource), new PropertyMetadata(null));

 

    public Type TargetType

    {

        get

        {

            return this.GetValue(TargetTypeProperty) as Type;

        }

        set

        {

            this.SetValue(TargetTypeProperty, value);

        }

    }

 

    public Object Parameter

    {

        get

        {

            return this.GetValue(ParameterProperty);

        }

        set

        {

            this.SetValue(ParameterProperty, value);

        }

    }

 

    public CultureInfo Culture

    {

        get

        {

            return this.GetValue(CultureProperty) as CultureInfo;

        }

        set

        {

            this.SetValue(CultureProperty, value);

        }

    }

 

    public IEnumerable ItemsSource

    {

        get

        {

            return this.GetValue(ItemsSourceProperty) as IEnumerable;

        }

        set

        {

            this.SetValue(ItemsSourceProperty, value);

        }

    }

 

    public IValueConverter Converter

    {

        get

        {

            return this.GetValue(ConverterProperty) as IValueConverter;

        }

        set

        {

            this.SetValue(ConverterProperty, value);

        }

    }

 

    IEnumerator IEnumerable.GetEnumerator()

    {

        foreach (var current in this.ItemsSource ?? new Object[0])

        {

            var targetType = this.TargetType ?? ((current != null) ? current.GetType() : null);

 

            yield return this.Converter.Convert(current, targetType, this.Parameter, this.Culture);

        }

    }

}

It inherits from DependencyObject, this is so that I can apply bindings to its properties. It will try to iterate through all the items in the ItemsSource property and convert one at a time using the supplied converter, culture and parameter. An example might be:

<UserControl.Resources>

    <my:TransformedItemSource x:Key="MyTransformer" ItemsSource="{Binding ItemsSource, ElementName=MyDatasource}" Converter="{StaticResource MyConverter}"/>

</UserControl.Resources>

<StackPanel x:Name="LayoutRoot">

    <ComboBox ItemsSource="{StaticResource MyTransformer}" Width="100" Height="30"/>

<StackPanel>

A nice way to use it is through a markup extension:

public class TransformExtension : DependencyObject, IMarkupExtension<IEnumerable>

{

    public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(TransformExtension), new PropertyMetadata(null));

    public static readonly DependencyProperty ConverterProperty = DependencyProperty.Register("Converter", typeof(IValueConverter), typeof(TransformExtension), new PropertyMetadata(null));

    public static readonly DependencyProperty ParameterProperty = DependencyProperty.Register("Parameter", typeof(Object), typeof(TransformExtension), new PropertyMetadata(null));

    public static readonly DependencyProperty CultureProperty = DependencyProperty.Register("Culture", typeof(CultureInfo), typeof(TransformExtension), new PropertyMetadata(CultureInfo.CurrentCulture));

    public static readonly DependencyProperty TargetTypeProperty = DependencyProperty.Register("TargetType", typeof(Type), typeof(TransformExtension), new PropertyMetadata(null));

 

    public Type TargetType

    {

        get

        {

            return this.GetValue(TargetTypeProperty) as Type;

        }

        set

        {

            this.SetValue(TargetTypeProperty, value);

        }

    }

 

    public Object Parameter

    {

        get

        {

            return this.GetValue(ParameterProperty);

        }

        set

        {

            this.SetValue(ParameterProperty, value);

        }

    }

 

    public CultureInfo Culture

    {

        get

        {

            return this.GetValue(CultureProperty) as CultureInfo;

        }

        set

        {

            this.SetValue(CultureProperty, value);

        }

    }

 

    public IEnumerable ItemsSource

    {

        get

        {

            return this.GetValue(ItemsSourceProperty) as IEnumerable;

        }

        set

        {

            this.SetValue(ItemsSourceProperty, value);

        }

    }

 

    public IValueConverter Converter

    {

        get

        {

            return this.GetValue(ConverterProperty) as IValueConverter;

        }

        set

        {

            this.SetValue(ConverterProperty, value);

        }

    }

 

    public IEnumerable ProvideValue(IServiceProvider serviceProvider)

    {

        return new TransformedItemSource { ItemsSource = this.ItemsSource, Parameter = this.Parameter, Culture = this.Culture, Converter = this.Converter };

    }

}

The TransformExtension class just delegates all of the work to the TransformedItemSource, but because it is a markup extension, it can be used as:

<ComboBox ItemsSource="{Binding ItemsSource, ElementName=MyDataSource, Converter={StaticResource MyConverter}}" Width="100" Height="30"/>

Enjoy!

Silverlight Method Data Source Markup Extension

A quick way to obtain a data source from a method through a markup extension, without any code:

<ComboBox ItemsSource="{my:MethodDataSource MethodName=GetItems}"/>

Implementation is simple:

public class MethodDataSourceExtension : DependencyObject, IMarkupExtension<Object>

{

    public static readonly DependencyProperty TargetProperty = DependencyProperty.Register("Target", typeof(Object), typeof(MethodDataSourceExtension), new PropertyMetadata(null));

    public static readonly DependencyProperty ArgumentProperty = DependencyProperty.Register("Argument", typeof(Object), typeof(MethodDataSourceExtension), new PropertyMetadata(null));


    public String MethodName { get; set; }


    public Object Target

    {

        get { return this.GetValue(TargetProperty); }

        set { this.SetValue(TargetProperty, value); }

    }


    public Object Argument

    {

        get { return this.GetValue(ArgumentProperty); }

        set { this.SetValue(ArgumentProperty, value); }

    }


    public Object ProvideValue(IServiceProvider serviceProvider)

    {

        var rootObjectProvider = serviceProvider.GetService<IRootObjectProvider>();

        var target = (this.Target ?? rootObjectProvider.RootObject);

        var method = target.GetType().GetMethod(this.MethodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public);

        var args = (this.Argument != null) ? new Object[] { this.Argument } : null;


        return method.Invoke((method.IsStatic == true) ? null : target, args);

    }

}

The MethodDataSourceExtension has three properties:

  • MethodName: the name of a method;
  • Target: the optional element from which the data source method will be retrieved; if not specified, the containing control (Page, UserControl, etc) will be used;
  • Argument: an optional argument to the data source method.

Because we might want to use bindings, the MethodDataSourceExtension class inherits from DependencyObject. This allows us to have:

<ComboBox ItemsSource="{my:MethodDataSource MethodName=GetItems, Target={Binding ElementName=SomeControl}}"/>

We can call any method, static or instance, as long as it is public. It can have a single parameter or no parameter at all.

Silverlight Resource Markup Extension

In case you want to use resources in your Silverlight applications, you have a couple of options. My favorite, however, is using a markup extension and RESX resource files. With this approach, you can have code such as:

<Button Click="OnClick" Content="{my:Resource ResourceName=Resources, ResourceKey=ButtonTitle}"/>

This is very similar to how you’d do it in ASP.NET web forms, and you can even share the resource files. Let’s see the ResourceExtension class, which, by implementing IMarkupExtension<T>, becomes a markup extension, meaning that by convention we can leave out the Extension suffix:

public sealed class ResourceExtension : IMarkupExtension<String>

{

    public String ResourceName { get; set; }

    public String ResourceKey { get; set; }

 

    private Type FindResourceType(params Assembly [] assemblies)

    {

        foreach (var assembly in assemblies.Distinct())

        {

            var resourceType = assembly.GetTypes().SingleOrDefault(x => (x.BaseType == typeof(Object)) && (x.Name == this.ResourceName));

 

            if (resourceType != null)

            {

                return resourceType;

            }

        }

 

        return null;

    }

 

    public String ProvideValue(IServiceProvider serviceProvider)

    {

        var executingAssembly = Assembly.GetExecutingAssembly();

        var callingAssembly = Assembly.GetCallingAssembly();

        var applicationAssembly = Application.Current.GetType().Assembly;

 

        var resourceType = this.FindResourceType(applicationAssembly, callingAssembly, executingAssembly);

 

        if (resourceType != null)

        {

            var resourceManager = new ResourceManager(resourceType);

            return resourceManager.GetString(this.ResourceKey);

        }

        else

        {

            throw new InvalidOperationException(String.Format("Cannot find resource {0} with key {1}.", this.ResourceName, this.ResourceKey));

        }

    }

}

ResourceExtension will try to find the class identified in the ResourceName property in a couple of assemblies and if it finds it, will try to return the resource key from the ResourceKey property; otherwise, it throws an exception, because, obviously, something is wrong.

The resource files need to be compiled as embedded resources:

image

Now, before you can use this, you need to do a couple of things:

  1. Add the NeutralResourcesAssemblyAttribute to your assembly to indicate which language the default resource file refers to (in AssemblyInfo.cs):
    [assembly: NeutralResourcesLanguage("en-US")]

  2. Set the culture of the current thread upon application startup (App.xaml.cs):
    private void Application_Startup(object sender, StartupEventArgs e)

    {

        Thread.CurrentThread.CurrentCulture = new CultureInfo("pt-PT");

        Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

     

        this.RootVisual = new MainPage();

    }

  3. Add the list of supported languages to the project file (.csproj):
    <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

      <PropertyGroup>

        <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>

        <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>

        <ProductVersion>8.0.50727</ProductVersion>

        <SchemaVersion>2.0</SchemaVersion>

        <ProjectGuid>{4AB634F1-D00D-4461-83F4-3ADA1DF2D47B}</ProjectGuid>

        <ProjectTypeGuids>{A1591282-1198-4647-A2B1-27E5FF5F6F3B};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>

        <OutputType>Library</OutputType>

        <AppDesignerFolder>Properties</AppDesignerFolder>

        <SupportedCultures>en-US;pt-PT</SupportedCultures>

        <TargetFrameworkIdentifier>Silverlight</TargetFrameworkIdentifier>

        <TargetFrameworkVersion>v5.0</TargetFrameworkVersion>

        <SilverlightVersion>$(TargetFrameworkVersion)</SilverlightVersion>

        <SilverlightApplication>true</SilverlightApplication>

        <!- ... -->

      </PropertyGroup>

    </Project>

And this is it! Enjoy!

Silverlight DynamicResource Markup Extension

This will be my first post on Silverlight!

WPF offers two markup extensions, StaticResource and DynamicResource, that can be used to set property values from items in resource dictionaries.

The difference between the two can be summarized as:

  • StaticResource is evaluated at the start of the application, and will find resources defined before its actual usage;
  • DynamicResource is evaluated at a later point, and will find resources declared anywhere, before or after its usage.

Unfortunately, Silverlight does not include DynamicResource, but it is relatively easy to achieve something like that; that is the purpose of this post.

Check out the following code:

public class DynamicResource : MarkupExtension

{

    public DynamicResource()

    {

    }


    public String ResourceName { get; set; }


    public override Object ProvideValue(IServiceProvider serviceProvider)

    {

        var provideValueTarget = serviceProvider.GetService<IProvideValueTarget>();

        var target = provideValueTarget.TargetObject as FrameworkElement;

        var property = provideValueTarget.TargetProperty as PropertyInfo;


        if (target != null)

        {

            RoutedEventHandler handler = null;

            handler = (sender, e) =>

            {

                var elm = sender as FrameworkElement;


                if (elm != null)

                {

                    var resource = TryFindResource(elm, this.ResourceName);

                    var typeConverterAttribute = property.GetCustomAttributes(typeof(TypeConverterAttribute), true).OfType<TypeConverterAttribute>().SingleOrDefault() ?? property.PropertyType.GetCustomAttributes(typeof(TypeConverterAttribute), true).OfType<TypeConverterAttribute>().SingleOrDefault();


                    if (typeConverterAttribute != null)

                    {

                        var typeConverterType = Type.GetType(typeConverterAttribute.ConverterTypeName, false);


                        if (typeConverterType != null)

                        {

                            var typeConverter = Activator.CreateInstance(typeConverterType) as TypeConverter;


                            if (typeConverter != null)

                            {

                                resource = typeConverter.ConvertFrom(resource);

                            }

                        }

                    }


                    property.SetValue(sender, resource, null);

                }


                target.Loaded -= handler;

            };


            target.Loaded += handler;

        }


        return (property.PropertyType.IsClass == true) ? null : Activator.CreateInstance(property.PropertyType);

    }


    private static Object TryFindResource(FrameworkElement element, Object resourceKey)

    {

        var currentElement = element;


        while (currentElement != null)

        {

            var resource = currentElement.Resources[resourceKey];

            if (resource != null)

            {

                return resource;

            }


            currentElement = currentElement.Parent as FrameworkElement;

        }


        return Application.Current.Resources[resourceKey];

    }

}

I won’t go into details on markup extensions and all that, but basically, this one hooks to the Loaded event of the FrameworkElement, thus deferring the setting of the property. The property and the target are found through the IProvideValueTarget instance and the resource is looked up recursively from the target element up to the Application instance. If the property to be set, or its class, defines a type converter, it will try to convert the found resource to the proper type.  In the meantime, it just returns the default value of the property type, null or a default instance, in case of a value type.