Posts tagged ‘Silverlight’

Silverlight (How To): Manipulation of Dynamic Selection Rubber Band in C#

Large group of women exercising in the parkOne of the basic tenets of WYSIWYG is to be able to create a rubber band region using the mouse to give the user the ability to create a selectable region. This article demonstrates how to do that in any version of Silverlight and the user is given the tools to create such a bounding rectangle in any circumstances via the usage of some basic building blocks in Silverlight.

The below picture (not the one on the left) shows our goal, the dynamic creation of a bounding rubber band (a rectangle control for this demonstration) in a canvas. The below canvas is drawn in black (visually grey due to the opacity set) while the bounding rectangle shows itself in red.


The user starts the process with an initial click which designates a start location of an upper left point for our bounding box with a mouse click.  Once the click happens the mouse cursor changes to a hand (if moving to the lower right) as a visible indicator that the process has started. While user continues to move to the lower right the band grows and while the mouse button has yet to be let go or released. For the demo a bounded number is shown is which relates the actual dynamic change in the X (horizontal) position. That is done for this article only and the above picture shows the rectangle with an X size of 123 pixels and can still be grown as shown by the hand icon.

Initial Xaml

In the page’s xaml we add a grid and a canvas as such this:

<Grid x:Name="LayoutRoot" Background="White">
        <RowDefinition Height="33*" />
        <RowDefinition Height="267*" />
        <ColumnDefinition Width="32*" />
        <ColumnDefinition Width="568*" />
    <Canvas x:Name="cMain"
        <TextBlock Width="100"
                    Text="{Binding XValue, ElementName=userControl}"
        <Rectangle Fill="Black"

The things to note are that the canvas is in a grid which is offset from the initial by 30 pixels in both axis. We then place a rectangle on the canvas which is our area which will be our strike zone where we will intercept the messages mouse events. We have a strike zone because individual controls in a canvas, such as texblocks have whitespace between them and the canvas will not get the mouse clicks and we want to be able to capture the process at all locations on the canvas; hence we fill up the canvas with our strike zone as to be ensured that the events are consumed properly by the code. 

When the user clicks within the strike zone the process starts as signified by a cursor change to the hand, as the user moves within the zone the rubber banding increases and when the mouse button is let up the process ends and the cursor is returned to its previous state.

Initial Properties

Here are the three variables we will use during this process:

private int _xValue;

public int XValue
    get { return _xValue; }
        _xValue = value;
        OnPropertyChanged( "XValue" );

private Point OriginatingPostionOnCanvas { get; set; }

private Rectangle RubberBandBox { get; set; }

Since the XValue property is reflected on the screen in a text box it reports all changes by using  INotifyPropertyChanged which our class handles in a standard way for notify property (not shown). Followed by that is our initial click location named OriginatingPostionOnCanvas which will dictate the upper left (or lower right) location of the rubber band rectangle which we will dynamically create. The last variable is the actual dynamic rectangle control named RubberBandBox which will be created and modified during the process.

Event Mouse Left Button Down

We will handle three events during this process. The first is the when the user clicks and begins to hold down the mouse button:

private void cMain_MouseLeftButtonDown( object sender, MouseButtonEventArgs e )
    OriginatingPostionOnCanvas = e.GetPosition( cMain );

    RubberBandBox = new Rectangle() { Width = 1, 
                                      Height = 1, 
                                      Fill = new SolidColorBrush( Colors.Red ), 
                                      Opacity = .1

    RubberBandBox.SetValue( Canvas.LeftProperty, OriginatingPostionOnCanvas.X);
    RubberBandBox.SetValue( Canvas.TopProperty,  OriginatingPostionOnCanvas.Y );

    cMain.Children.Add( RubberBandBox );

Our goals here are simple:

  1. Get and store the location where the user clicked in relation to the canvas.
  2. Create  and store the rectangle in red and with an opacity which does allows the user to see what is being selected.
  3. Setting the initial location of the rectangle and adding it to the children of the canvas.

Event Mouse Move

The user is moving and we must adjust the rectangle as appropriate for the target direction. Note we also have to handle when the user moves to the upper left instead of the lower right…. So when that happens we will change the cursor to a Stylus (the dot) for visual indication that we are getting a reverse band situation.

private void cMain_MouseMove(object sender, MouseEventArgs e)
    if (RubberBandBox == null)

    Point pointMovedTo = e.GetPosition( cMain );

    double xDelta = pointMovedTo.X - OriginatingPostionOnCanvas.X;
    double yDelta = pointMovedTo.Y - OriginatingPostionOnCanvas.Y;

    LayoutRoot.Cursor = ((xDelta > 0) && (yDelta > 0)) ? Cursors.Hand : Cursors.Stylus;

    if (LayoutRoot.Cursor == Cursors.Hand)
        RubberBandBox.Height = yDelta;
        RubberBandBox.Width  = xDelta;
    else if (LayoutRoot.Cursor == Cursors.Stylus)
        RubberBandBox.Height = Math.Abs( yDelta );
        RubberBandBox.Width = Math.Abs( xDelta );

        if (xDelta < 0)
            RubberBandBox.SetValue( Canvas.LeftProperty, pointMovedTo.X );

        if (yDelta < 0)
            RubberBandBox.SetValue( Canvas.TopProperty, pointMovedTo.Y );

    XValue = (int) (e.GetPosition( cMain ).X - OriginatingPostionOnCanvas.X);
Line 3 The mouse can move through the canvas during times we are not processing. We need to check that and only process when we have an actual rectangle on the canvas.
Line 6 Extract the current location in relation to the canvas.
Line 8-9 Get the change differences for x and y as named deltas.
Line 11 If the deltas retrieved are in the positive we have a drag to the lower right and that is designated by or specifying the cursor to a hand. If not, the deltas indicate that movement is upwards and to the left; regardless change the  cursor to the stylus.
Line 13 If we are in the hand state, we want to grow (or decrease) the rectangle in that direction towards the lower right.
Line 18 If we are in the stylus state, there is a negative growth either in the x or y axis. Handle the negatives while changing the height and width. Depending on which delta is negative, handle the new location position of the upper left hand position of our bounding rectangle which will follow the mouse.
Line 30 Inform the user of the current X axis location of the mouse whether positive or negative.

Event Mouse Left Button Up

This is our final event we have to handle. We do a safety check on whether we are actually in operations, and if we are then we simply return the cursor to its original state and remove the rectangle from the canvas’ children.

private void cMain_MouseLeftButtonUp( object sender, MouseButtonEventArgs e )
    if (RubberBandBox == null)

    // Return to the previous state; whatever it is, the OS handles it.
    LayoutRoot.Cursor = null; 

    cMain.Children.Remove( RubberBandBox );

    // Show that we are not processing by making this null.
    RubberBandBox = null; 

Xaml: Adding Visibility Behaviors Using Blend to A DataGrid for WPF or Silverlight

iStock_000015143879XSmallIn Xaml the determining when to trigger the visibility, or the hiding of  controls or their functionality is a key concept of doing either WPF or Silverlight programming. This article builds upon my article C#: WPF and Silverlight DataGrid Linq Binding Example Using Predefined Column Header Names in Xaml where we are going to add behaviors to the datagrid shown.  (Don’t worry about reading the article, for I will get you up to speed with the code snippets in this article.) We will use Microsoft’s Expression Blend product to do the dirty work of xaml modification to our DataGrid and it will be shown in a step by step process.


In the previous article the idea was to load our datagrid with two columns of data. The first column showed us a filename and the second column displayed a modified filename with a count in it. We will take that one step further and have a description show up with the file size. Here is the resulting look:

Inital with Description

The user gets the description when the row is clicked.

But what if we wanted to disable that functionality and automatically show the user all the items when the mouse hovers over the datagrid such as



First thing we need to do is setup our datagrid. Below is the xaml and the code behind to load our datagrid. Note the datagrid has the RowDetailsVisibiltyMode set to collapsed. That means that when a user clicks on the row, it will only select it and not open up our description. The loading of the ItemsSource happens during the construction and after the initial initialization and is shown in C# in the second pane.

<DataGrid x:Name="dgPrimary"

            <TextBlock FontWeight="Bold"
                        Text="{Binding Size, StringFormat=Size \{0\} (bytes)}" />

        <DataGridTextColumn Binding="{Binding Original}"
                            Header="File Name Before"
                            IsReadOnly="True" />
        <DataGridTextColumn Binding="{Binding New}"
                            Header="File Name After"
                            IsReadOnly="True" />
dgPrimary.ItemsSource = 
    new DirectoryInfo( "c:\\" ).GetFiles()
                               .Select( ( fInfo, index ) => new
                        Original = fInfo.Name,
                        New = string.Format( "{0}_{1}{2}", 
                                    System.IO.Path.GetFileNameWithoutExtension( fInfo.Name ), 
                                    System.IO.Path.GetExtension( fInfo.Name ) ),
                        Size = fInfo.Length
                    } );

Behaviors and Blend

One of the easiest ways to add a behavior [of the action] to a control is to use Blend to add an interaction behavior.  In our case we want a mouse over action to open up all of the Row Details and a secondary action to close them when the mouse leaves. The behavior we need to search for in blend is the ChangePropertyAction. Below we drag (or add) two behaviors to the datagrid and change the RowDetailsVisibilityMode to visible on mouse enter and to collapsed on mouse leave.

cpaEnter cpaLeave

Then when we build and run the app, the mouse hover over makes the descriptions visible and collapsed depending on the mouse. Here is the final xaml:

<DataGrid x:Name="dgPrimary"

            <TextBlock FontWeight="Bold"
                        Text="{Binding Size, StringFormat=Size \{0\} (bytes)}" />

        <DataGridTextColumn Binding="{Binding Original}"
                            Header="File Name Before"
                            IsReadOnly="True" />
        <DataGridTextColumn Binding="{Binding New}"
                            Header="File Name After"
                            IsReadOnly="True" />
        <i:EventTrigger EventName="MouseEnter" SourceObject="{Binding ElementName=dgPrimary}">
            <ei:ChangePropertyAction x:Name="cpaEnter" PropertyName="RowDetailsVisibilityMode">
        <i:EventTrigger EventName="MouseLeave">
            <ei:ChangePropertyAction x:Name="cpaLeave"
                PropertyName="RowDetailsVisibilityMode" />

C# Silverlight: Codebehind Binding Between Two Controls Example

Here is a quick example of binding between two controls on the same xaml page. I have provided both ways of doing the binding the first in xaml and the second in the code behind. The first example is the most common method of binding in xaml while the other is the code behind, a more dynamic binding situation. 

Sometimes it helps to see a contrast if one is used to one or the other, a translation of sorts; so here it is:

Xaml Binding

The goal is to have the custom Slidebox control’s Spacing property to be bound to the TickTrack Control’s SpacingMargin property since these two controls have to work together (think of a slider control on a timeline).

If one were to do this in xaml it would look like this

    SecondsEnd="{Binding SecondsEnd, ElementName=userControl}"
    SecondsStart="{Binding SecondsStart, ElementName=userControl}"
    TickFrequency="{Binding TickFrequency, ElementName=userControl}" 
    HorizontalAlignment="Left" Width="{Binding Width, ElementName=userControl}" Height="59" Canvas.Top="70" />

<my:SlideBox Spacing="{Binding SpacingMargin, ElementName=tkTrack}"  />

The slidebox spacing is now uses the named tkTrack control’s dependent property  (not shown but publicly available property on TickTrack).

Code Behind Binding

If one were to do the same in code behind, say for a dynamically created custom slidebox control:

var bndSpacing = new Binding() 
                        Source = tkTrack, // Not the name but actual instance object
                        Path = new PropertyPath( "SpacingMargin" ) 

var sb = new SlideBox();

// "{Binding SpacingMargin, ElementName=tkTrack}"
sb.SetBinding( SlideBox.SpacingProperty,
               bndSpacing );

We create a binding instance with  the actual source and the path setup similar to xaml but different. The Source is not a named source but the actual object for the source to be bound to. Once we have the object, we then specify that the new slide box instance is to set the binding to the SpacingProperty (of the class description) dependency property of the slidebox instance.

Hope This Helps


C# Silverlight WCF: Thread Safe Multiple Async Call Strategy With Final Operation To Join Data.

Seven Pointing Arrows ending at different points except one arror leaping of the page to show the final Async call.This article describes one way to handle asynchronous or async calls in .Net 3.5 or .Net 4.0 when using WCF in Silverlight in C#. The goal is to have a final operation wait for all the calls to finish so to combine all the data gathered, all in a thread safe way. A secondary goal is to minimize the consumer code required to perform this operation from what is currently available in straight WCF async calls.

This article has a short shelf life because after .Net 4 (see What’s Next in C#? Get Ready for Async!) one will use the built in Asynchrony methodology developed. Until that time if one is using any version of Silverlight and WCF then this article describes how to handle those multiple async calls and join the data in a final method call.

Final Result Example

Before delving into the solution, here is how the consumer will use the methodology. Below a user is getting account information of user requests, departments and accounts to join all the data on the view model in the final method for display on a Silverlight page. Thesee operations as shown are setup when the view model class (MyViewModel) is created and no blocking occurs keeping UI thread clear.

public MyViewModel()
    DataContext = new MyServiceClient();

    FinalAsync(CombineDataAndDisplay); // When all the data is retrieved, do this method to combine the data From the 3 async callls below

    // Provide the operation as a lambda (could be a method call) to assign data to our target backing store property
    // and if all has gone well (no errors in other async calls) and it is the final completing operation. Do the final
    // Processing call automatically.
    DataContext.GetUserRequestsCompleted   += (s, e) => { AssignResultCheckforAllAsyncsDone(e, e.Result, ref _UserRequests, "Acquisition failure for User Requests");};
    DataContext.GetAccountsCompleted       += (s, e) => { AssignResultCheckforAllAsyncsDone(e, e.Result, ref _Accounts, "Acquisition Failure for Accounts"); };
    DataContext.GetDepartments             += (s, e) => { AssignResultCheckforAllAsyncsDone(e, e.Result, ref _Departments, "Failed to get Department Info."); };   

    // Start the Async processes 

    // Exit out and return the UI thread to the user operations.

// Once all the data is done, combine and assign into our
// PagedCollectionView property for display on the screen.
public void CombineDataAndDisplay()
    // Combine missing data on the calls
                .ForEach(ur =>
                ur.BillingName     = _Accounts.First(ac => ur.AccountID == ac.AccountID).Name;
                ur.DepartmentName  = _Departments.First(dp => dp.DepartmentID == ur.DepartmentID).Name;

    UserRequests = new PagedCollectionView( _UserRequests);
    UserRequests.GroupDescriptions.Add(new PropertyGroupDescription("DepartmentName"));

Line  5: The final async call is where this process specifies a method to use after all async calls are completed. On line 24 of the example is our final operation method to do that which is reported to FinalAsync.
Line 11-13: Just like the normal async process we subscribe to the anync handler but we handle it in a anonymous lambda.
Line 11-13: AssignResultCheckForAllAsyncsDone method will check the result returned, code show later in the article. All one needs to know now is that the respective _UserRequests, _Accounts and _Departments, all backing store variables (not properties) will be loaded with the data if the result information ( e ) operation contains no errors. This method does all the heavy lifiting by checking error state, loading the data variable, decrementing the async count and firing off the final method if all asynchronous operations are completed.
Line 16-18: Just like the normal WCF async process we must launch the asnc calls and these statements do just that. We supply the method to be launched inside the MulipleAsync method.
Line 24: Here is our final method to be executed once the asynchrony process is complete. This method combines all the async data internally into the _UserRequest object at which it becomes complete and can be used.
Line 34: Finally a paged collection view is created from our data to be bound to Silverlight Xaml items which is our end result.
24-37: Note: The section below has a variable entitled AsyncErrors. The above example did not check that for null or an error situation. I have left out the check of AsyncErrors for brevity of the example. See the last section for an example of proper error handling.

Multiple Async Methodology Plumbing

Below is what will needed to be brought into your View Model, or placed on your page if not using MVVM. This is where the .Net thread safe Silverlight asynchronous operations will occur.

// Lock Objects 0 for false, 1 for true.
private int AsyncErrorResource = 0;
private int AsyncFinal = 0;

private List<Exception> AsyncErrors;  // If not null errors have been encountered.

private int PendingAsyncOperations; // Holds the counted total of ongoing async operations. Zero means do users final operation.

private Action FinalOperation;      // The user's final operation.

public void MultipleAsyncRun(Action Operation)
    Interlocked.Increment(ref PendingAsyncOperations);

public void FinalAsync(Action method)
    FinalOperation = method;

public void AssignResultCheckforAllAsyncsDone<T>(AsyncCompletedEventArgs ea, T receivedData, ref T assignTo, string ErrorMessage)
   where T : class
    bool valid = !((ea.Error != null) || (receivedData == null));

    if (valid == false)
        if (0 == Interlocked.Exchange(ref AsyncErrorResource, 1))
            if (AsyncErrors == null)
                AsyncErrors = new List<Exception>();


            //Release the lock
            Interlocked.Exchange(ref AsyncErrorResource, 0);
        assignTo = receivedData;

    Interlocked.Decrement(ref PendingAsyncOperations);
    if (PendingAsyncOperations == 0)
        if (0 == Interlocked.Exchange(ref AsyncFinal, 1))

        Interlocked.Exchange(ref AsyncFinal, 0);
        Interlocked.Decrement(ref PendingAsyncOperations); // Move to -1
Line  2/3: These variables are used as a lock targets for thread safety. Value zero means its open and a value of 1 means a lock is in place.
Line  5: Any errors encountered are placed into AsyncErrors. The final operation must check this variable. If it is not null errors have occurred and data is incomplete see the final section of this article on how to handle errors.
Line 7: This variable will hold the running total async operations. Once it gets to zero the final operation will be executed.
Line 11: This method counts and stores our async operations as they come in and launches the async method as well.
Line 13: This process uses the Interlocked class found in the System.Threading namespace. To quote Microsoft, “Provides atomic operations for variables that are shared by multiple threads. “. We simply count up the PendingAsyncOperations variable. Later when the operations complete this will be decremented.
Line 18: This method is called by the consumer so we know what method to launch when all async operations have completed. We assign the method to a holder variable as found on line 9.
Line 22: This method will take in the event arguments and check if there is a problem. It will store the error if there is one and also decrement our count. If our count hits zero it will launch the users final operation.
25-39: Checking errors reported by the async call. If there are any we log them and do not assign the variable. Note whether an error exists or not the operation continues below where the final operation is checked for and executed. Its up to the final operation to check if errors exists and handle them appropriately.
Line 42: If the event reports a success this is where we assign the value to the passed in reference to the template T assignTo. If one doesn’t use a variable for assignTo reference an exception will be generated on this line. See the following section as to why. 
Line 46: We safely decrement our operations count variable. Zero means we are done!
Line 47-57: Here is where we execute the final operation when the count is zero. Note there is an extra lock if operations unlikely hit a zero at the same time. The extra lock ensures only one will execute the final method.

That is it, simply use the above code and you can have all your operations work done asynchronously. Smile Now for the disclaimers…

Why Can’t Properties be Used by AssignResultCheckforAllAsyncsDone?

We must use direct variables like in our example

private ObservableCollection<UserRequestDTO> _UserRequests;
private ObservableCollection<Account> _Accounts;
private ObservableCollection<Department> _Deparments;

// Not Private ObservableCollection<Department> _Departments { get; set; }

If one used a property this exception is thrown.

A property, indexer or dynamic member access may not be passed as an out or ref parameter

That is because we are using the generic method AssignResultCheckforAllAsyncsDone to assign a value, and that assignment has to have an exact object instance for the template (T) object and not a Property to assign the value. If your end result is in a property, simply assign it from the variable to the property in the final async call.

Handling Errors

Simply check the error variable if it is not null it has encountered errors.

if (AsyncErrors != null)
    MessageBox.Show("Errors: " + string.Join(string.Format("{0}{0}", Environment.NewLine), AsyncErrors.Select(ex => ex.Message)));
    // Success Handle accordingly.

Silverlight: Xaml Blend Namespace Error Not Resolved

XAML Namespace is not resolved.

This error can occur when certain Xaml elements added by blend have not been properly ignored during non design/debug situations and Blend or Visual Studio reports such error.

To resolve the error one must add the mc:Ignorable attribute to the namespace declarations to inform the Xaml compiler to ignore a specific specified namespace at appropriate times. T0 fix the above error where the blend namspace is qualified by d one needs to ingore D as shown on the highlighted line:


How Does This Happen?

I ran into this recently when Blend 4 added Xaml to allow me to populate (bind generated data) to a datagrid during design time (only in blend mind you) to work with the design data. Of course the blend namespace was there, but it never added the ignorable. It actually failed due from this line because its bringing in the blend namespace here, though I was never informed of the exact line.

<Grid x:Name="LayoutRoot"
      d:DataContext="{d:DesignData /SampleData/HomeViewModelSampleData.xaml}">

One can see the ‘d’ namespace qualifier which relates to the blend namespace declaration as shown above. Since its job is to bring in sample data, that obviously should not be expressed during runtime and was not ignored.

Once one understands this situation the resolution seems trivial but it is one which has to be learned.


C#: WPF and Silverlight DataGrid Linq Binding Example Using Predefined Column Header Names in Xaml

iStock_000015057287XSmallThis snippet is from my archives and reminds me how to setup column names for a WPF/Silverlight datagrid and bind them to the data by not using AutoGenerateColumn feature. (See below for the visual end result.)

Ω Check out the related post Xaml: Adding Visibility Behaviors Using Blend to A DataGrid for WPF or Silverlight

DataGrid Column Names Setup in Xaml

In this example we will have two columns where the data will be filename strings. We will specify the columns in the Xaml to use the DataGridTextColumn and not to dynamically generate columns on our Datagrid:

<DataGrid x:Name="dgOperation" AutoGenerateColumns="False">
        <DataGridTextColumn Header="File Name Before" Binding="{Binding Path=Original}"/>
        <DataGridTextColumn Header="File Name After"  Binding="{Binding Path=New}"/>

The result is that the header row will have two columns with the name “File Name Before” and “File Name After” will subsequently bind them to a data object with the property names of “Original” and “New”.

Actual Binding During the Loading of the Grid

We will read in a directory for the WPF example from the hard drive and fill the original file names to the first column and a generated name for the second column. Since we have specified in the Xaml that we are binding to “Original” and “New” properties the dynamic linq object created will have those properties.

dgOperation.ItemsSource = Directory.GetFiles( @"C:\" )
                                   .Select( ( nm, index ) => new
                                          Original = System.IO.Path.GetFileName( nm ),
                                          New = string.Format( "{0}_{1}{2}", System.IO.Path.GetFileNameWithoutExtension( nm ),
                                                                             System.IO.Path.GetExtension( nm ) )
                                        } );

The result is as below:


Note: Out of the box editing the rows will throw an exception. To fix that make each of the rows read only.


Visual Studio: Downloaded Assembly Gives "ValidateXaml" task failed unexpectedly Error or FileLoadException

This is a How To Fix when you have downloaded a foreign (to your computer) assembly which can occur when dealing with Silverlight assemblies but it applies to all assemblies downloaded. Here is more of the errors:

error MSB4018: The "ValidateXaml" task failed unexpectedly.

error MSB4018: System.IO.FileLoadException: Could not load file or assembly ‘… \ImageSequence.dll’ or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)

System.NotSupportedException: An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See for more information.

The situation is that the OS has identified that the assembly was not made on the computer and has been blocked. This is usually the case with downloaded assemblies and is a security feature.

Steps To Resolve

  1. In Visual Studio in the Solution Explorer Window right click on the project which contains the dll and select Open Folder in Windows Explorer.
  2. In Windows Explorer find the dll in question and right click and select Properties.
  3. Select Unblock and select OK. (As shown below)


  4. Rebuild.

Once you see the properties and this text its more self explanatory than the Visual Studio error.

This file came from another computer and might be blocked to help protect this computer.


Remember that .Net is an Xcopy install. Meaning that any .Net application can be installed by simply copying over the assemblies. The OS recognizes the assemblies and categorizes them for running. When one copies code over and tries to manipulate it in Visual Studio the OS blocks for safety reasons and it subsequently fails during a Visual Studio build.