CoreCLR's Blog

Archive for the ‘Silverlight’ Category

Display a messagebox from the ViewModel using Prism’s InteractionRequests

Posted by coreclr on January 5, 2011

Prism has a nice feature called InteractionRequests. We can use this when the view-model needs to initiate an interaction, like displaying a messagebox.

Below is a simple example:


In XAML I define the PopupChildWindowAction to display the dialog to the user.  The visuals of this dialog is defined in the SaveWindowsTemplate.
The magic here is the InteractionRequestTrigger from Prism. I set the SourceObject to the SaveRequest that is defined in the ViewModel.

SaveRequest is a InteractionRequest that define a Raise method, that we can use to raise the event.

I then use a interaction trigger to call the Cancel method in the viewmodel.  See Preview post.


And the result look like this:


Posted in .NET, Silverlight | Leave a Comment »

Using interaction triggers in MVVM

Posted by coreclr on January 5, 2011

Commands are ofter to limited when using the MVVM pattern. Instead we can use interaction triggers.

Here is a simple example of handling the MouseEnter event for a button in a viewModel.



The key point here is the CallMethodAction object. CallMethodAction is a TriggerAction defined in the Microsoft.Expression.Interactivity.Core namespace. In this example I set TargetObject to the DataContext (the viewModel) and MethodName to the method we want to call in the ViewModel.

If you need to send parameters to the method, you just expose those as properties in the viewModel and use standard DataBinding.

Remember to reference Microsoft.Expression.Interactions.dll

Posted in .NET, Silverlight | Leave a Comment »

Silverlight course – demo and slides

Posted by coreclr on February 4, 2010

Thanks to everyone who participated in the Silverlight course this week.

All demos and slides are now uploaded to Live Mesh.

Posted in Kursus, Presentations, Silverlight | Leave a Comment »

Silverlight Feature Request: Allow Network Communication on Application Exit

Posted by coreclr on December 6, 2009

If you would like native .NET access to calling Web Services on Application Exit, then vote here:

Posted in .NET, Silverlight, Threading | Leave a Comment »

Silverlight Tip: Finding UI elements from mouse position

Posted by coreclr on December 6, 2009

Say you click on a UI element, and you want to know if you clicked a specific type.

Lets say you have this tree, and you want to know if you have clicked on a TabItem:

<Grid x:Name="LayoutRoot">
     <controls:TabControl Margin="100">
         <controls:TabItem Header="TabItem">
         <controls:TabItem Header="TabItem">

In this case we can use the FindElementsInHostCoordinates method. First we subscribe to the MouseLeftButtonUp event.

public MainPage()
   this.MouseLeftButtonUp +=  new MouseButtonEventHandler(MainPage_MouseLeftButtonUp);

We then get the  mouse position:

var position = e.GetPosition(null);

We can then use the FindElementsInHostCoordinates method and pass in the position. This will give us an IEnumerable of UIElement’s.

var elements = VisualTreeHelper.FindElementsInHostCoordinates(position, this);

We can now use a linq Query to select the TabItem elements:

var tabItems = from element in elements
               where element is TabItem
               select element;

And then we can test if there was a hit:

if (tabItems.Count() == 1)
     MessageBox.Show("TabItem was hit");


Posted in Silverlight | Leave a Comment »

How to expand TreeViewItems from right to left in Silverlight

Posted by coreclr on November 28, 2009

In this post I am going to show how we can change the Silverlight TreeView Template to support expanding TreeViewItems from right to left.
The text on the items should still be left-to-right and the text should be right alligned.

First we will build a normal TreeView with some data.

We define a HierarchicalDataTemplate:

      <common:HierarchicalDataTemplate x:Key="MyHierarchicalTemplate" ItemsSource="{Binding Items}" >
          <TextBlock Text="{Binding Title}" />

And this is the TreeView that will use the HierarchicalDataTemplate:

<controls:TreeView VerticalAlignment="Stretch" 
          ItemTemplate="{StaticResource MyHierarchicalTemplate /> 

Then we define a simple class to hold the data:

public class DataItem
      public string Title { get; set; }
      public ObservableCollection<DataItem> Items { get; set; }

      public DataItem(string title, params DataItem[] items)
          this.Title = title;
          ObservableCollection<DataItem> itemsObservableCollection =
              new ObservableCollection<DataItem>();

          foreach (var item in items)

         Items = itemsObservableCollection;

And in our MainPage we populate the TreeView with some data:

public partial class MainPage : UserControl
        ObservableCollection<DataItem> itemsSource;
        public MainPage()
            treeView.ItemsSource = itemsSource;

        private void AddData()
            itemsSource = new ObservableCollection<DataItem>()
                 new DataItem("Europe",
                    new DataItem("Denmark"),
                    new DataItem("Norway"),
                    new DataItem("Sweden")),
                  new DataItem("USA",
                    new DataItem("New York",
                        new DataItem("Albany"))),

When we run this, we get a simple TreeView like this:


So far, so good. Now lets change the Template so we can get the TreeView to display the items from Right to Left.

We open Blend and edit the ItemContainerStyle Template:


First set HorizontalContentAlignment and HorizontalAlignment to right:

<Setter Property="HorizontalContentAlignment" Value="Right"/>
<Setter Property="HorizontalAlignment" Value="Right"/>

Now locate the Grid element, and change the definition to this:

   <ColumnDefinition Width="Auto"/>
   <ColumnDefinition Width="15"/>
   <ColumnDefinition Width="*"/>
   <RowDefinition Height="Auto"/>
   <RowDefinition Height="*"/>

Now located the Selection Rectangle element and set these two properties:


Now located the Header Button element and set these properties:


Next locate the ContentPresenter and set HorizontalAlignment:


Then locate the ItemsPresenter element and set these properties:


Now Locate the ExpanderButton and set these properties:


Now we will use a RotateTransform to rotate the ExpanderButton. Add this:

              <RotateTransform Angle="-180"/>

Now add a RotateTransform to the CheckedVisual Path element. We rotate that –90.

     <RotateTransform Angle="-90"/>

That’s it!

Set the ItemContainerStyle on the TreeView to our new Template:

ItemContainerStyle="{StaticResource RightToLeftViewItemStyle}"

Run and you should see the Items expanding from right to left with the text alligned to the right:


Get the code here.

(rename it to .zip)

Posted in .NET, Silverlight | Leave a Comment »

Silverlight 4 kursus

Posted by coreclr on November 26, 2009

Fra den 1. til 4. februar 2010 afholder Thomas Martinsen og undertegnede et Silverlight 4 kursus.

Kurset henvender sig til udviklere som vil i gang med at udvikle “Line of Business” applikationer med Microsoft Silverlight 4.

Det bliver fire intensive dage hvor vi kommer rundt om en meget stor del af de features der ligger i Silverlight.

Information og tilmeldning sker her.

Posted in Kursus, Presentations, Silverlight, Talk | Leave a Comment »

Async chain of service calls in Silverlight

Posted by coreclr on November 26, 2009

A colleague of mine asked me how to chain service calls in a Silverlight async model.

Lets say you have these two operations:

string GetId()
void Calculate(string id)

And you must call GetId first and then use the result of that operation to call the Calculate operation.

The solution is pretty simple. We can use our old friend; the AutoResetEvent class. Luckly this exist in Silverlight as well.

First we put the task on the ThreadPool so we don’t block the UI Thread:

private void Button_Click(object sender, RoutedEventArgs e)

And here is the StartWork method:

public void StartWork(object state)
    var dataService = new DataServiceClient();
    var personService = new PersonServiceClient();

           string id = string.Empty;
           dataService.GetIdCompleted += (s, e) =>
               id = e.Result;

               //signal the event, so the thread can continue

           //call GetIdAsync

           //pause the thread

           //call CalculateAsync with the id

Thats it. Pretty simple.

Posted in .NET, Silverlight, Threading | Leave a Comment »

Silverlight 4 Security Overview White Paper

Posted by coreclr on November 20, 2009

Nick Kramer from Microsoft created a great whitepaper about Silverlight Security. Get it here.

Posted in Silverlight | Leave a Comment »

Silverlight 4 Beta

Posted by coreclr on November 18, 2009

Today we can download a beta version of Silverlight 4.

The tools are here and Expression Blend are here.

Silverlight 4 has a lot of nice features. If you have done any LOB WPF development, you will be very happy to see these new features in Silverlight 4:

– Trusted applications (COM Interop, file-access, network)
– Printing Support
– Right-click context menu
– Clipboard access Support
– Better Data Binding support (grouping/editing, StringFormat)
– Implicit Styling
– RichTextbox support
– IDataErrorInfo support
– Build-in mouse wheel support
– Webcam and microphone support
– Network credentials support (authentication)
– WCF NetTcp Binding
– UDP Multicast Support
– Profiler and Profiler API
– Out of browser Window settings (position, size, chrome)
– Notification windows (toast)
– Embedding HTML (WebBrowser control)
– Same compiled code to be run on the desktop and Silverlight

and off course WCF RIA Services

This page describe all the new features and this page describe known bugs in Silverlight 4.

And finally this page describe a Technical Feature Overview.

Posted in .NET, Silverlight, WPF | Leave a Comment »