Posted by Davide on Apr 19, 2010 in
- Silver Light |
View Original Article
If you are looking for a rich toolbar control for Silverlight, check out this project on CodePlex by Silverlight MVP Braulio Diez and Sebastian Stehle:
http://wintoolbar.codeplex.com/
Tags: - news, - Programming, - Virtualization, .NET Programming, Application Packaging, Open Source, ria, Rich Internet Applications, Silver Light, Silverlight 4
Posted by Davide on Apr 5, 2010 in
- Silver Light |
View Original Article
In the last example I’ve implemented a new “MEF Module” organized with a MVVM approach and using Prism Event Aggregator to exchange messages.
This new module could be used to partititon the application in several XAPs composed dynamically at run-time using MEF, the new DeploymentCatalog and the Navigation features available in Silverlight.
To start I’ve created a new “Silverlight Navigation Application” which produces a complete application with ready-to-use navigation and localization.
Then I’ve inserted a new “Silverlight User Control” inside the “Views” folder and named it “MEFModuleContainer“: this one is called by the navigation framework and is responsible to load dynamically the module using the MEF “DeploymentCatalog“.
This is the XAML of the container:
<StackPanel x:Name="ContentStackPanel">
<TextBlock x:Name="HeaderText" Style="{StaticResource HeaderTextStyle}"
Text="MEF Module container"/>
<TextBlock x:Name="ContentText" Style="{StaticResource ContentTextStyle}"
Text="MEF content"/>
<ItemsControl x:Name="content"/>
</StackPanel>
Our “MEF Module” is hosted in a “ItemsControl” using the “Items” property:
public MEFModuleContainer()
{
InitializeComponent();
CompositionInitializer.SatisfyImports(this);
CatalogService.AddXap("MEFModule.xap");
}
[Import]
public IDeploymentCatalogService CatalogService { get; set; }
[ImportMany(AllowRecomposition = true)]
public Lazy<UserControl>[] MEFModuleList { get; set; }
#region IPartImportsSatisfiedNotification Members
public void OnImportsSatisfied()
{
MEFModuleList.ToList()
.ForEach(module=>
content.Items.Add(module.Value)
);
}
#endregion
In order to use the DeploymentCatalog, it’s necessary to define an interface “IDeploymentCatalogService“ (read this post by Glenn Block for more information about it):
public interface IDeploymentCatalogService
{
void AddXap(string uri, Action<AsyncCompletedEventArgs> completedAction = null);
void RemoveXap(string uri);
}
and implement it in the class “DeploymentCatalogService“:
[Export(typeof(IDeploymentCatalogService))]
public class DeploymentCatalogService : IDeploymentCatalogService
{
private static AggregateCatalog _aggregateCatalog;
Dictionary<string, DeploymentCatalog> _catalogs;
public DeploymentCatalogService()
{
_catalogs = new Dictionary<string, DeploymentCatalog>();
}
public static void Initialize()
{
_aggregateCatalog = new AggregateCatalog();
_aggregateCatalog.Catalogs.Add(new DeploymentCatalog());
CompositionHost.Initialize(_aggregateCatalog);
}
public void AddXap(string uri, Action<AsyncCompletedEventArgs> completedAction = null )
{
DeploymentCatalog catalog;
if (!_catalogs.TryGetValue(uri, out catalog))
{
catalog = new DeploymentCatalog(uri);
if (completedAction != null)
catalog.DownloadCompleted += (s, e) => completedAction(e);
else
catalog.DownloadCompleted += catalog_DownloadCompleted;
catalog.DownloadAsync();
_catalogs[uri] = catalog;
_aggregateCatalog.Catalogs.Add(catalog);
}
}
void catalog_DownloadCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
throw e.Error;
}
public void RemoveXap(string uri)
{
DeploymentCatalog catalog;
if (_catalogs.TryGetValue(uri, out catalog))
{
_aggregateCatalog.Catalogs.Remove(catalog);
}
}
}
The DeploymentCatalogService is initialized during the Application startup in this way:
private void Application_Startup(object sender, StartupEventArgs e)
{
//Initialize the DeploymentCatalogService for MEF
DeploymentCatalogService.Initialize();
this.RootVisual = new MainPage();
}
When the user clicks on the Navigation bar, the container is loaded and filled with the content of the external XAP, all managed by MEF:

So we have a Navigation application which can dynamically load external “MEFModules” organized with a MVVM approach, contained in external XAPs and using an Event Aggregator to exchange messages, all managed by MEF.
This application can be easily extended inserting WCF RIA Services and/or Blend sample data for the design mode.
As usually the sample code is available for download here and will be soon available in the CodePlex project “MEF MVVM” – http://mefmvvm.codeplex.com.
Happy Silverlighting!
Tags: - Programming, - Virtualization, .NET Programming, Application Packaging, Patterns, ria, Rich Internet Applications, Silver Light, Silverlight, Silverlight 4
Posted by Davide on Apr 5, 2010 in
- Silver Light |
View Original Article
I’ve just updated the project on CodePlex http://multitouch.codeplex.com to Silverlight 4 RC and added a new sample of multi-touch using Windows Phone 7 manipulation capabilities starting from this how-to available in MSDN – “How to: Handle Manipulation Events” - http://msdn.microsoft.com/en-us/library/ff426933(VS.96).aspx.
The modified sample uses an Image to illustrate the possibility to move and scale objects in the Windows Phone emulator using the “ManipulationDelta” event:

These are the steps to follow in order to enable Scale and Translation gestures in a Windows Phone application:
- Just create a new “Windows Phone Application” from Visual Studio and then add an Image control in the MainPage.xaml using this code
<Canvas x:Name="ContentCanvas" Grid.Row="1">
<Image Source="Images/Desert.jpg" Canvas.Left="99" Canvas.Top="100"
x:Name="image1" Stretch="Fill" Width="300">
</Image>
</Canvas>
- Then add an event handler for the “ManipulationDelta” event for applying a Scale and a Translate transform using the CompositeTransform available in Silverlight 4:
public MainPage()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;
ManipulationDelta += image1_ManipulationDelta;
_compositeTransform=new CompositeTransform();
image1.RenderTransform = _compositeTransform;
}
private CompositeTransform _compositeTransform;
void image1_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
// Scale
if (e.DeltaManipulation.Scale.X!=0)
_compositeTransform.ScaleX *= e.DeltaManipulation.Scale.X;
if (e.DeltaManipulation.Scale.Y!=0)
_compositeTransform.ScaleY *= e.DeltaManipulation.Scale.Y;
// Translation
_compositeTransform.TranslateX += e.DeltaManipulation.Translation.X;
_compositeTransform.TranslateY += e.DeltaManipulation.Translation.Y;
}
The source code is available for download from CodePlex: http://multitouch.codeplex.com
Happy Silverlighting!
Tags: - Programming, - Virtualization, .NET Programming, Application Packaging, Multi-Touch, New Technology, ria, Rich Internet Applications, Silver Light, Silverlight 4, UX - Design, Windows Phone
Posted by Davide on Apr 4, 2010 in
- Silver Light |
View Original Article
I have already blogged about using Blend behaviors to add Multi-Touch gestures and inertia effects to a generic Silverlight user control, so I wanted to use the same approach to add the same behaviors to the CodePlex project Simon.

I think that inserting multi-touch manipulation effects to a Silverlight application using Blend behaviors is an elegant way which makes the code very clear and readable.
To start you need to download the Multi-touch manipulation and inertia behavior (wow, more than 7000 downloads, great feedback!
), which I already published on the Expression site.
This behavior is based on the code available in the Microsoft Surface Manipulations and Inertia Sample for Microsoft Silverlight, in my opinion the best example available for using multi-touch in Silverlight at this time.
The solution available contains a project named “MultiTouch.behaviors.Silverlight” which must be included in your application to enable the multi-touch functionalities.
To make the Silverlight/Blend Behavior work with Simon I’ve modified some code relative to the Zoom gesture in order to use a ScaleTransform (check out the source code on CodePlex: http://simon.codeplex.com).
To use the Behavior in XAML just add a reference to the “MultiTouch.Behaviors.Silverlight” project and use the following code:
<UserControl x:Class="SimonSilverlight.MainPage"
....
xmlns:interactivity="clr-namespace:System.Windows.Interactivity; assembly=System.Windows.Interactivity"
xmlns:multitouch="clr-namespace:MultiTouch.Behaviors.Silverlight; assembly=MultiTouch.Behaviors.Silverlight">
....
<Canvas>
<uc:Simon x:Name="Says">
<interactivity:Interaction.Behaviors>
<multitouch:MultiTouchManipulationBehavior InertiaEnabled="True" TouchRotateEnabled="True"
TouchScaleEnabled="True" TouchTranslateEnabled="True"/>
</interactivity:Interaction.Behaviors>
</uc:Simon>
</Canvas>

Since we are using a Blend Behavior, we can also open the solution in Expression Blend, select the “MultiTouchManipulationBehavior” from the “Assets” section and drag it over the Simon control:

Happy Silverlighting!
Tags: - Programming, - Virtualization, .NET Programming, Application Packaging, Expression, Multi-Touch, New Technology, ria, Rich Internet Applications, Silver Light, Silverlight, Silverlight 4, UX - Design
Big news today from the MIX conference in Las Vegas: a new Silverlight 4 RC release and Windows Phone development using Silverlight.
While watching the event I’ve put together some links, check it out!
Silverlight 4 RC
Want to know what’s new in Silverlight 4 RC? Check out this doc.
As usually all the bits can be downloaded from the “Get Started“ section of the official site.
Other useful links:
Windows Phone links:
Happy Silverlighting!
Tags: - news, - Virtualization, .NET Programming, Application Packaging, ria, Rich Internet Applications, Silver Light, Silverlight, Silverlight 4, Windows Phone
Posted by Davide on Mar 13, 2010 in
- Silver Light |
View Original Article

.toolbox is a free online training program where designers and developers can learn to create Silverlight applications using Expression Studio and to apply basic UX concepts to their solutions.
Check out the original post by Adam Kinney and the main site.
Happy Silverlighting!
Tags: - news, - Virtualization, Application Packaging, education, Expression, ria, Rich Internet Applications, Silver Light, Silverlight, UX - Design
Posted by Davide on Jan 6, 2010 in
- Miscelleneous |
View Original Article
I’ve updated the behavior available in the Expression Community gallery adding Multi-Touch manipulation (translation, rotation and zoom) and inertia effects using code from the Surface Manipulations and Inertia Sample for Microsoft Silverlight.
To enable Multi-Touch in your code simply download the behavior from here, add the project “MultiTouch.Behaviors.Silverlight” to a Visual Studio solution and then enable the gestures in XAML:
<UserControl x:Class="SilverlightMultiTouch.MainPage"
...
xmlns:interactivity="clr-namespace:System.Windows.Interactivity; assembly=System.Windows.Interactivity"
xmlns:behaviors="clr-namespace:MultiTouch.Behaviors.Silverlight; assembly=MultiTouch.Behaviors.Silverlight"
...
>
<Canvas>
<Image Source="Images/Desert.jpg">
<interactivity:Interaction.Behaviors>
<behaviors:MultiTouchManipulationBehavior InertiaEnabled="True"
TouchRotateEnabled="True" TouchTranslateEnabled="True" TouchScaleEnabled="True"/>
</interactivity:Interaction.Behaviors>
</Image>
<Image Source="Images/Jellyfish.jpg">
<interactivity:Interaction.Behaviors>
<behaviors:MultiTouchManipulationBehavior InertiaEnabled="True"
TouchRotateEnabled="True" TouchTranslateEnabled="True" TouchScaleEnabled="True"/>
</interactivity:Interaction.Behaviors>
</Image>
</Canvas>
The MultiTouchManipulationBehavior also contains some dependency properties (TouchRotateEnabled, TouchTranslateEnabled, TouchScaleEnabled and InertiaEnabled) to enable the corresponding gestures.
The example contains Multi-Touch manipulations applied to some Image controls and a Smooth streaming player of the Silverlight Media Framework.

I’ve also posted to CodePlex a sample using WPF 4 based on the article “Introduction to WPF 4 Multitouch“ by Jaime Rodriguez.
Hope this helps and Happy Silverlighting!
Tags: - Programming, - Virtualization, .NET, .NET Programming, Application Packaging, New Technology, ria, Rich Internet Applications, Silver Light, Silverlight 3, Silverlight 4, UX, UX - Design, WPF
Posted by Davide on Dec 13, 2009 in
- Miscelleneous |
View Original Article
Note – this is a multi part post:
Today I had the opportunity to take a look at the code written in the previous posts and insert some new stuff in order to modify the project and make new experiments about:
-
using a different ViewModel class for the design-time and run-time;
-
-
retrieve the data using an async call to a WCF service and passing back the results to the VM via MEF.
1 – Using different VM classes
To accomplish this task I’ve defined a new interface named IMainPageViewModel defining these members:
/// MainPage ViewModel interface
public interface IMainPageViewModel : IViewModelBase
{
string aViewModelProperty { get; set; }
DataItems dataItems { get; set; }
ICommand addDataItemCommand { get; }
}
This new interface is then implemented by two classes named ViewModels.DesignMode.MainPageViewModel and ViewModels.MainPageViewModel:
/// ViewModel for the "MainPageView" used in design-mode
public class MainPageViewModel : ViewModelBase, IMainPageViewModel
{
public MainPageViewModel()
{
//Initialize the properties with test data if design mode
aViewModelProperty = "Value - Design Mode";
//Initialize the "dataItems" property
dataItems = new DataItems();
dataItems.Add(new DataItem() { Description = "Sample Data Item 1 - Design Mode" });
dataItems.Add(new DataItem() { Description = "Sample Data Item 2 - Design Mode" });
}
public string aViewModelProperty { get; set; }
public DataItems dataItems { get; set; }
public ICommand addDataItemCommand { get; set; }
}
/// ViewModel class for the "MainPageView" using MEF
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(MainPageViewModel))]
public class MainPageViewModel : ViewModelBase, IMainPageViewModel
{
public MainPageViewModel() { }
[Import("aViewModelPropertyTextProvider")]
public string aViewModelProperty { get; set; }
[Import(typeof(WcfDataItems))]
public DataItems dataItems { get; set; }
[Import(typeof(ICommand))]
public PartCreator<ICommand> addDataItemCommandCreator { get; set; }
private ICommand _addDataItemCommand;
public ICommand addDataItemCommand
{
get {
if (_addDataItemCommand==null)
_addDataItemCommand = addDataItemCommandCreator.CreatePart().ExportedValue;
return _addDataItemCommand;
}
}
}
The first one is associated with the View at design-time using an attached property which permits to bind an instance only at design time using this xaml (usually you should use <d:DesignProperties.DataContext>, here we are experimenting, of course):
<UserControl x:Class="SL4_MVVM_MEF.Views.MainPageView"
........
xmlns:designer="clr-namespace:SL4_MVVM_MEF.Designer"
xmlns:providersDM="clr-namespace:SL4_MVVM_MEF.Providers.DesignMode"
>
<!-- Design time DataContext -->
<designer:Page.DesignDataContext>
<providersDM:MainPageViewModelProvider/>
</designer:Page.DesignDataContext>
........
DesignTimeDataContext attached dependency property:
/// DesignDataContext Attached Dependency Property
public static readonly DependencyProperty DesignDataContextProperty =
DependencyProperty.RegisterAttached("DesignDataContext", typeof(object), typeof(Page),
new PropertyMetadata((object)null,
new PropertyChangedCallback(OnDesignDataContextChanged)));
/// Gets the DesignDataContext property.
public static object GetDesignDataContext(DependencyObject d)
{
return (object)d.GetValue(DesignDataContextProperty);
}
/// Sets the DesignDataContext property.
public static void SetDesignDataContext(DependencyObject d, object value)
{
d.SetValue(DesignDataContextProperty, value);
}
/// Handles the DesignDataContext property changes
private static void OnDesignDataContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)d;
//Get the ViewModel instance only in design mode
if ((Application.Current == null) || (Application.Current.GetType() == typeof(Application)))
element.DataContext = e.NewValue;
}
And this is the design-time mode in Blend using the new attached property:

2 – MEF and implicit styles
The new implict styles feature available in Silverlight 4 beta is used to initialize the DataContext of the MainPageView type in a declarative way in App.xaml:
<Application xmlns="http://schemas.microsoft.com/winfx/2006/ xaml/presentation"
xmlns:x= "http://schemas.microsoft.com/winfx/2006/xaml"
x:Class= "SL4_MVVM_MEF.App"
xmlns:views= "clr-namespace:SL4_MVVM_MEF.Views"
xmlns:providers= "clr-namespace:SL4_MVVM_MEF.Providers">
<Application.Resources>
<!-- Run-time DataContext composed using MEF -->
<Style TargetType="views:MainPageView">
<Setter Property="DataContext">
<Setter.Value>
<providers:MainPageViewModelMEFProvider/>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
</Application>
In this case I’ve modified the MainPageViewModelMEFProvider class and inserted a new IViewModelProvider interface in order to obtain the instance of the ViewModel initialized by MEF:
/// Interface for the ViewModelProvider
public interface IViewModelProvider
{
object GetViewModel { get; }
}
/// Get the ViewModel instance using MEF
public class MainPageViewModelMEFProvider : IViewModelProvider
{
public MainPageViewModelMEFProvider() { }
[Import(typeof(MainPageViewModel))]
public IViewModelBase ViewModel { get; set; }
/// Get the Instance of the ViewModel using MEF
public object GetViewModel
{
get
{
PartInitializer.SatisfyImports(this);
return ViewModel;
}
}
}
3 – retrieve the data using an async call to a WCF service
I’ve added to the solution a simple WCF service which returns a collection of DataItems:
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class DataItemService : IDataItemService
{
[OperationContract]
public List<DataItemFromService> GetDataItems()
{
// Add your operation implementation here
return new List<DataItemFromService>()
{
new DataItemFromService() {Description="DataItem from service 1"},
new DataItemFromService() {Description="DataItem from service 2"},
new DataItemFromService() {Description="DataItem from service 3"}
};
}
}
interface IDataItemService
{
List<DataItemFromService> GetDataItems();
}
public class DataItemFromService
{
public string Description { get; set; }
}
Since the project uses MEF composition and [Import] /[Export] attributes to initialize all the members of the VM class, I’ve used the same approach for the dataItems collection, retrieving data from an async call to the WCF service using a WcfDataItems class:
/// A sample collection of DataItems from WCF
[Export(typeof(WcfDataItems))]
public class WcfDataItems : DataItems
{
public WcfDataItems()
{
//Initialize the collection
DataItemWcfService.DataItemServiceClient svc = new DataItemWcfService.DataItemServiceClient();
svc.GetDataItemsCompleted += (s1, e1) =>
{
if (e1.Result != null)
e1.Result.ToList().ForEach(d =>
{
//Retrieve a new DataItem
DataItem di = DataItemCreator.CreatePart().ExportedValue;
di.Description = d.Description;
this.Add(di);
});
isLoading = false;
};
svc.GetDataItemsAsync();
isLoading = true;
}
[Import(typeof(DataItem))]
public PartCreator<DataItem> DataItemCreator { get; set; }
}
The code is available for download here.
Happy Silverlighting!
Tags: - Programming, - Virtualization, .NET Programming, Application Packaging, Patterns, ria, Rich Internet Applications, Silver Light, Silverlight 4
Posted by Davide on Dec 7, 2009 in
- Miscelleneous |
View Original Article
In the last post I’ve updated the sample project introducing PartCreator<T>, in this one I will illustrate a method to make available sample data during the editing of the solution in Blend or in the Visual Studio designer, in order to obtain a result like this (a similar approach is used in the awesome MVVM light toolkit by Laurent Bugnion):

First of all, I’ve created a class ViewModelProvider to obtain dinamically an instance of the ViewModel and directly used in xaml to create the VM instance, in this way it’s possibile to see sample data during the design phase:
public class ViewModelProvider : IViewModelProvider
{
public ViewModelProvider() { }
[Import(typeof(MainPageViewModel))]
public IViewModelBase mainPageViewModelProvider { get; set; }
/// <summary>
/// Get the Instance of the ViewModel
/// </summary>
public IViewModelBase GetVMInstance
{
get
{
//Verify if Design Mode
if ((Application.Current == null) || (Application.Current.GetType() == typeof(Application)))
{
return new MainPageViewModel();
}
else
{
//If not in Design Mode uses MEF to compose the objects
PartInitializer.SatisfyImports(this);
return mainPageViewModelProvider;
}
}
}
}
I’ve not already found a method to activate MEF compositions during design time, so an instance of the ViewModel class is explicitely created in code if we are in the tool designers, otherwise SatisfyImports() executes the MEF magic as usually.
It’s now necessary to initialize the properties values in order to display sample data at design time, this step can be done in the constructor of the MainPageViewModel:
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(MainPageViewModel))]
public class MainPageViewModel : ViewModelBase, IMainPageViewModel
{
///
/// Default constructor
///
public MainPageViewModel()
{
if ((Application.Current == null) || (Application.Current.GetType()==typeof(Application)))
{
//Initialize the properties with test data if design mode
aViewModelProperty = "Value - Design Mode";
dataItems = new SampleDataItems(); dataItems.ToList().ForEach(d=>d.Description+=" - Design Mode");
}
}
///
/// A sample property
///
[Import("aViewModelPropertyTextProvider")]
public string aViewModelProperty { get; set; }
///
/// A sample collection
///
[Import(typeof(DataItems))]
public DataItems dataItems { get; set; }
///
/// A Part creator for the addDataItemCommandCreator
///
[Import(typeof(ICommand))]
public PartCreator addDataItemCommandCreator { get; set; }
private ICommand _addDataItemCommand;
public ICommand addDataItemCommand
{
get {
if (_addDataItemCommand==null)
_addDataItemCommand = addDataItemCommandCreator.CreatePart().ExportedValue;
return _addDataItemCommand;
}
}
}
Inside Visual Studio, it’s now possibile to edit the User Interface and visualize the sample data defined in the constructor:

The source code is available for download here.
Hope this helps!
Tags: - Programming, - Virtualization, .NET Programming, Application Packaging, Patterns, ria, Rich Internet Applications, Silver Light, Silverlight 4