Faster Invoke for reflected property access and method invocation with AOT compilation
Posted by whydoidoit in Project With Code on April 18, 2012

The bane of the iOS programmers life, when working with reflection in Mono, is that you can’t go around making up new generic types to ensure that your reflected properties and methods get called at decent speed. This is because Mono on iOS is fully Ahead Of Time compiled and simply can’t make up new stuff as you go along. That coupled with the dire performance of Invoke when using reflected properties lead me to construct a helper class.
This works by registering a series of method signatures with the compiler, so that they are available to code running on the device. In my tests property access was 4.5x faster and method access with one parameters was 2.4x faster. Not earth shattering but every little helps. If you knew what you wanted ahead of time, then you could probably do a lot better. See here for info.
You have to register signatures inside each class I’m afraid. Nothing I can do about that.
So to register a signature you use:
static MyClass()
{
//All methods returning string can be accelerated
DelegateSupport.RegisterFunctionType<MyClass, string>();
//All methods returning string and taking an int can be accelerated
DelegateSupport.RegisterFunctionType<MyClass, int, string>();
//All methods returning void and taking a bool can be accelerated
DelegateSupport.RegisterActionType<MyClass, bool>();
}
Then when you have a MethodInfo you use the extension method FastInvoke(object target, params object[] parameters) to call it. FastInvoke will default to using normal Invoke if you haven’t accelerated a particular type.
myObject.GetType().GetProperty("SomeProperty").GetGetMethod().FastInvoke(myObject);
myObject.GetType().GetMethod("SomeMethod").FastInvoke(myObject, 1, 2);
You can download the source code for FastInvoke from here.
Fixing the width of strings displayed in the Unity GUI
Posted by whydoidoit in Project With Code on April 12, 2012
Firstly, I know what you are going to say – you should just use two aligned labels, rather than fiddling around with string formatting – but sometimes that just doesn’t work – like when you want the items in a popup to have columns like here:
No chance for using labels in that component. So there is a way of effectively padding text to a given width. You basically work out the width of a ” “, a tab and the string, then use that combination to make a new string which is the correct width.
Just using string.PadRight(20) doesn’t work due to the variable width of characters in the font.
public static class TextHelper
{
public static string FixTo(this string str, float width, string type="label")
{
var widthOfTab = GUI.skin.GetStyle(type).CalcSize(new GUIContent("\t")).x;
var widthOfSpace = GUI.skin.GetStyle(type).CalcSize(new GUIContent(" ")).x;
var widthOfString = GUI.skin.GetStyle(type).CalcSize(new GUIContent(str)).x;
return str + new String(' ', (int)((width-widthOfTab)/widthOfSpace)+1) + "\t";
}
}
You basically use myString.FixTo(150) to fix it based on the width of a “label” in the skin or you can override it to set a different font by using myString.FixTo(200, “box”).
Should work fine in javascript so long as you make a .cs file out of this and put it in your plugins folder.
Extended Unity Coroutines
Posted by whydoidoit in Project With Code on April 7, 2012

I really like the coroutine pattern in unity but unfortunately it’s not possible to directly extend it. What I would really like is to be able to write cut scene and NPC logic in a single routine, but I need to do things like wait for an animation to complete or an AI task goal to be achieved. Not being able to write my own YieldInstructions I took to the keyboard and wrote an extended coroutine system that uses as Unity’s existing stuff as a base.
To use it you can download and install the package, then when you want to start an extended coroutine you use:
StartCoroutine( RadicalRoutine.Run(yourEnumeratorFunction()) )
YOU MUST insert the RadicalRoutine.Run inside the StartCoroutine call or not much will happen!
Note it only works with the none “text” based version of StartCoroutine at the moment.
Now you can write your own classes that indicate the completion status, they inherit from CoroutineReturn and can set or override two key values.
- finished – set to true / or override and return true when the action has finished
- cancel – set to true / or override and return true if you want the whole coroutine to be aborted
I’ve included one that waits for a part of an animation (end or some point in the middle) to complete and a version that waits for the weight of some animation to reach a value (I use this to keep my blended animations smooth in cut scenes). It’s called WaitForAnimation and there’s an extension class that adds methods to GameObject: gameObject.WaitForAnimation(name, normalizedTime /* default 1f */) and gameObject.WaitForAnimationWeight(name, weight /* default 0f */);
You can also yield any standard Unity YieldInstruction like WWW, WaitForSeconds etc.
You can use the coroutine functions from c# or javascript.
Example
Here’s an example of me using the extensions to run a complete sequence for an NPC. Obviously in this example I’m calling routines in my game that aren’t listed, but they all return CoroutineReturn instances that pause execution until the task is complete. You can see me using the WaitForAnimation and WaitForAnimationWeight methods directly.
What I want to do is move my character over to a table, pick up an envelope, show it to the player and then put it back down again afterwards.
IEnumerator MoveToPosition_EnterState()
{
Vector3 envAngle;
//Store the current position of the envelope to be picked up
var rot = msg.transform.rotation;
var parent = msg.transform.parent;
var pos = msg.transform.position;
//Find the point that will carry the envelope
var ch = gameObject.GetComponentInChildren();
//Move the character to the envelope's location
yield return MoveTo((lookPt = msg.transform.Find("EnvelopeLook")).position);
//Look at the envelope
yield return RotateTo(envAngle = lookPt.rotation.eulerAngles);
yield return new WaitForSeconds(0.3f);
//Play the pickup animation
Animate("pick_up_from_table");
//Wait until half way through
yield return gameObject.WaitForAnimation("pick_up_from_table",0.5f);
//Put the envelope in the carry point
msg.transform.parent = ch.transform;
msg.transform.localPosition = Vector3.zero;
msg.transform.localRotation = Quaternion.Euler(0,0,0);
//Wait for the pickup animation to complete
yield return gameObject.WaitForAnimation("pick_up_from_table");
yield return new WaitForSeconds(0.2f);
//Turn to face the camera
yield return RotateTo(new Vector3(0,10,0));
//Wait for the rotation animations to complete
yield return gameObject.WaitForAnimationWeight("left_turn"); //Without a specified second parameter waits for 0
yield return gameObject.WaitForAnimationWeight("right_turn");
//Play the excited animation
yield return Animate("excited");
yield return new WaitForSeconds(0.5f);
//Raise the hand containing the envelope
yield return Animate("hand_raising");
yield return new WaitForSeconds(1.5f);
yield return Animate("hand_raising");
yield return new WaitForSeconds(2.5f);
//Wave move dramatically
yield return Animate("waving");
yield return new WaitForSeconds(0.5f);
//Turn around to face the table
yield return RotateTo(envAngle);
//Play the pickup animation
Animate("pick_up_from_table");
//Wait for it to be 40% complete
yield return gameObject.WaitForAnimation("pick_up_from_table",0.4f);
//Put the envelope back on the table
msg.transform.parent = parent;
msg.transform.position = pos;
msg.transform.rotation = rot;
//Wait for the animation to complete
yield return gameObject.WaitForAnimation("pick_up_from_table");
//Rotate to face the camera
yield return RotateTo(new Vector3(0,10,0));
//Look over shoulder at envelope
yield return Animate("looking_behind");
//Sigh
yield return Animate("relieved_sigh");
yield return new WaitForSeconds(1);
//Finish activity
BlackboardComplete();
}
Additional
You can also call RadicalRoutine.Create(yourCoRoutineFunction()) which returns an RadicalRoutine instance that can be cancelled. To use that you pass the instances enumerator property to StartCoroutine like this:
r = RadicalRoutine.Create(myRoutine());
StartCoroutine(r.enumerator);
…
r.Cancel(); //Abort on the next iteration
Also the RadicalRoutine has events for cancellation and completion called Cancelled and Finished.
Unity curved path following with easing at constant speed
Posted by whydoidoit in Programming, Project With Code on April 6, 2012
The Problem
I have a character than needs to follow paths curved through a series of control points as it moves around the world. I also want to ease in and out to speed of movement as the path starts and ends. Sometimes in the middle of a path follow I need to change my mind and have some other path taken or perhaps change from path following to another state. This isn’t possible with iTween at constant speed unless you use PutOnPath, which doesn’t allow easing functions. I would also like to be able to move at a constant speed – either by ignoring the length of individual path elements (and thereby specifying at time fraction for the whole path) or by having a maximum speed my object can travel at.
Solution
Building on the great work done by Andeeee and Renaud, I’ve made a path following class that enables you to specify from 2 to N points and have it build a curved path (if it has more than 2 points!), you can then follow that path using a time from 0…1 and also apply an easing function to make the start and the end points smooth.
It supports Linear, Sine, Quadratic, Cubic, Quintic and Quartic easing functions with control on over whether the path is eased in and out separately.

Line 1 – EaseIn, Line 2 – EaseOut, Line 3 – EaseIn and EaseOut
This allows fine grained control of an eased, spline path in an Update function that is not possible using iTween – this enables you to abort a movement halfway through if something more important is happening .
To use it you download and import the unity package.
Eased spline paths
To use no easing call Spline.Interp(arrayOfPoints, time). Where time is a float between 0 and 1.
The array of points can be an array of Vector3s, GameObjects or Transforms which are implicitly converted to a Spline.Path instance containing an array of Vector3s. DON’T BOTHER to create your own Spline.Path instances!
e.g. transform.position = Spline.Interp(myPathObject.GetComponentsInChildren<Transform>(), time);
This would use the myPathObject and all of its children to define the path. (For example only, don’t go calling GetComponentsInChildren every frame).
To ease the function you can supply one or more of the easing parameters:
Spline.Interp(arrayOfPoints, time, easingType /* e.g. EasingType.Sine */, easeIn /* e.g. true (default) */, easeOut /*e.g. false (default true) */ );
The Spline class also supports Andeeee’s Velocity and GizmoDraw functions to help you with debugging.
PLEASE NOTE: the function uses a different algorithm for short paths so that you can get a number of different effects. If your path has 2 points it does a linear interpolation, 3 points does a Quadratic spline and 4 points does a Cubic spline. The 5 or more point version uses Catmul Rom splines and ensures that the path passes through every point.
You can double up start and end points easily with the Spline.Wrap() call on your path array – you may want to do this for short paths if you want to ensure that all of the points are passed through – or just do it yourself. There should be no effect if you are using InterpConstantSpeed or MoveOnPath when you do this (See below).
Constant Speed
I’ve added an InterpConstantSpeed function too, this tries to make the speed of movement constant between sections. It works in the same way as Interp, with a time value between 0 and 1.
Now just a note on that. If your path points are moving then you need to watch constant speed interpolations as one section getting much longer or shorter could cause the position to vary wildly. If your path sections are increasing or decreasing in size then you are better off using Interp and trying to make sure that each path section is roughly the same size (short sections will appear to have lower velocity than large sections, so they need to be “kind of” the same size). Interp says if your path has 5 sections, each one takes 1/5 of the time to cross. If you are in section 2 and section 3 gets bigger, you will complete section 2 in the normal time. Using constant speed, the position at time “t” is along the magnitude of the whole path, if it gets longer or shorter then the position at “t” will change between sections moving the Vector unrealistically forwards or backwards. This is a problem if you are in an early stage of the path and a later path point, far off screen, is moving. The Vector will stutter for apparently no reason. If you want constant speed then you need to ensure that your path points maintain exactly the same distance from each other when they move (they need to move in an arc centered on the previous end point).
The second point is that applying “Constant Speed” and “Easing” appears to create a paradox; but InterpConstantSpeed accepts easing functions! Well the “Constant” bit refers to the sizes of path sections being converted to a path magnitude and the easing is applied to the “time” fed into the path calculator: so you can have your cake and eat it
Path Movement and Character Speed
I’ve also added a speed limited version, this also solves the constant speed issue by having a maximum possible movement speed, you can therefore move those path elements as often as you like – but you can’t specify the time it takes to complete the path. It works kind of like a SmoothDamp – here’s how you go about it:
public class TestFollow : MonoBehaviour {
public Transform[] path;
float t = 0;
// Update is called once per frame
void Update () {
transform.position = Spline.MoveOnPath(path, transform.position, ref t, 0.5f);
}
}
Basically you pass the path, the current position and a reference to a float that will contain the currently targeted path point, the final parameter shown here is the number of world units per second to move.
This routine also has the added benefit that it will move to the start of the path before following it.
Here are all of the parameters to MoveOnPath:
| Parameter | Meaning |
| pts | An array of transforms, Vector3s or GameObjects that describe the path |
| currentPosition | The current position of the object being moved |
| pathPosition | The position along the path, this is updated by the call so must be a variable of the class |
| (Optional)rotation | A quaternion that will be updated to show the rotation that should be used. This can change quickly for slow moving objects, so you might want to smooth it. See below. |
| maxSpeed | The maximum number of world units to move in one second, default is 1 |
| smoothnessFactor | The smoothing factor is the number of steps on the path that will be used, default is 100 |
| ease | The type from EasingType.Linear, EasingType.Sine, EasingType.Cubic, EasingType.Quadratic, EasingType.Quartic and EasingType.Quintic. Default is Linear |
| easeIn | true if you want to ease in the function or false if you don’t. Default is true |
| easeOut | true if you want to ease out the function or false if you don’t. Default is true |
Here’s an example of the version that returns a rotation, in this example I use the SmoothQuaternion from a previous post to smooth out the rotations.
#pragma strict
var pathPoints : Transform[];
var t : float;
var sr : SmoothQuaternion;
function Start() {
sr = transform.rotation;
sr.Duration = 0.5f;
}
function Update () {
var q : Quaternion;
transform.position = Spline.MoveOnPath(pathPoints, transform.position, t, q, 0.5f, 100, EasingType.Sine, true, true);
sr.Value = q;
transform.rotation = sr;
}
Javascript
You can use the Spline class from JavaScript, as long as the .cs files are somewhere inside a Assets/Plugins folder (the download does this) and that JavaScript is not inside a Plugins folder.
This example will follow a constant speed path for 20 seconds.
#pragma strict
var pathPoints : Transform[];
var t : float;
function Update () {
transform.position = Spline.InterpConstantSpeed(pathPoints, t, EasingType.Sine, true, true);
t += Time.deltaTime/20;
}
The next one moves an item on a path at a maximum of 0.5 world units per second
#pragma strict
var pathPoints : Transform[];
var t : float;
function Update () {
transform.position = Spline.MoveOnPath(pathPoints, transform.position, t, 0.5f, 100, EasingType.Sine, true, true);
}
Smoothed Vector3, Quaternions and floats in Unity
Posted by whydoidoit in Project With Code on April 1, 2012

I’ve put together a set of structs to handle changing the values of floats, Vector3s and Quaternions over time. It’s very simple to use and is far easier to read than having lots of time recognising code or referenced veclocities in the middle of your game logic. You replace a Vector3 (say) with a SmoothVector3 in your code, set its target value, smoothing method and duration, then read its value over time in an Update() call. I use this when I don’t have a gameObject to hand to apply iTween or when I may want to keep changing the position and don’t want to mess with iTween and need the control at every Update call.
You can choose a smoothing mode from slerp, lerp, SmoothDamp and SmoothStep.
To use this in your code, download the .cs file and put it in your Assets/Plugins folder.
Here is an example from JavaScript on how to use the SmoothVector3 to smoothly move an object when a key is pressed.
#pragma strict
var pos : SmoothVector3;
function Start () {
//Construct a SmoothVector3 by assigning a normal Vector3
//this initializes the position
pos = transform.position;
//The following are optional and override the standard settings
//Duration in seconds of the transform
pos.Duration = 1;
//Smoothing mode from damp, smooth, lerp and slerp
pos.Mode = SmoothingMode.damp;
}
function Update () {
if(Input.anyKeyDown)
{
//Setting the Value of the SmoothVector3 starts the interpolation
//This will move the item 1 unit in X,Y from the current position
//(which may be an interpolated value)
pos.Value = pos.Value + Vector3(1,1,0);
//In this example this is equivalent to
//pos.Value = transform.position + Vector3(1,1,0);
//An alternative is to use the .Target property
//which is the current targeted position - in our example
//this maintains the object on exact boundaries and means
//that it will accelerate if you click lots of times
//pos.Value = pos.Target + Vector3(1,1,0);
//Or of course you could just set the value
//pos.Value = Vector3(100,100,0);
}
//A SmoothVector3 can be used in place of a Vector3 in assignments
transform.position = pos;
}
With Vector3 and Quaternions you can directly affect the individual elements to set the targeted value.
mySmoothVec3.x = mySmoothVec3.x + 100;
Unity terrain avoiding smart follow camera
Posted by whydoidoit in Project With Code on March 22, 2012

I’ve been needing a terrain avoiding follow camera, I couldn’t find one that was exactly right so I produced my own.
My script uses multiple different methods to keep the followed object in view:
* Desired location with the camera adjusted for terrain height
* Rise above structures
* Zoom in to be closer to the followed object
* Camera rotation (cut view) to a different angle
Each method can be weighted to give the effect that you prefer. Each method votes on how aggressive a movement it had to make in order to locate the camera in an unobstructed location, the winner gets to set the location of the camera.
You can download it here.
Here is it in operation – I’m moving the camera a bit to put it in difficult places, but mostly it’s under the control of the system.
Unity automatic MeshCollider generation
Posted by whydoidoit in Project With Code on March 22, 2012
When ever I get a model that has many sub elements, but no standard mesh colliders I use the wizard listed here to automatically generate them. Thought it might come in useful to others…
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Linq;
public class AddColliders : ScriptableWizard {
[MenuItem("Wizards/Add Mesh Colliders")]
static void CreateWizard()
{
ScriptableWizard.DisplayWizard<AddColliders>("Add mesh colliders", "Add Colliders");
}
void OnWizardCreate()
{
if(UnityEditor.Selection.activeGameObject != null)
{
foreach(var c in UnityEditor.Selection.activeGameObject.GetComponentsInChildren<MeshRenderer>().Cast<MeshRenderer>().
Where(mr=>mr.GetComponent<MeshCollider>()==null))
{
c.gameObject.AddComponent(typeof(MeshCollider));
}
}
}
void OnWizardUpdate()
{
helpString = "Add mesh colliders to all items that have a mesh renderer";
}
}
Updated WordCloud Component
Posted by whydoidoit in Uncategorized on August 17, 2011
I’ve updated the WordCloud component and added some documentation that you can find here: http://whydoidoit.com/wordcloud-for-silverlight
The new component supports individual word colouring and word angle.
SilverlightSerializer Version 2
Posted by whydoidoit in Project With Code on August 5, 2011
SilverlightSerializer version 2
Well, I know it’s been a long wait and I’ve been promising the new version of SilverlightSerializer for months, but it’s finally here, extracted from my core project and working standalone.
This new version of the serializer is a major rewrite – with 2 goals in mind:
1. Performance
Serialization performance is 61% faster (my test harness serializes 100,000 objects in 1.03 seconds compared to 1.72)
Deserialization performance is 27% faster (my test hardness deserializes 100,000 objects in 1.61 seconds compared to 2.04)
These performance gains are on large object graphs containing multiple instances of the same types – it would nominally be slightly slower on small graphs or graphs that contain only one copy of each object – but of course that’s very unlikely in the real world.
2. Extensibility
The new version of SilverlightSerializer abstracts the storage methods behind a new interface, IStorage. There’s a complete implementation of a BinarySerializer that is compatible with the old version of SilverlightSerializer, but you could add your own. Alterian has built versions that store data in XML and SQL Server tables. This means one standard semantic serialization layer can be used with pluggable storage types to put the information where you need it for the application at hand.
That said, writing an IStorage is fairly involved process and I’ll write a post or a page on it if people want me to.
In addition the serializer now handles arrays and enums far better than before and hopefully should avoid the dreaded MissingMethod exception by providing a more developer friendly exception and message while offering the opportunity to construct classes without a parameterless constructor using a new CreateType event that will help some avoid the need to write custom serializers.
You can find the version 2 source code here. In response to a couple of requests, the project is also accessible on GitHub, see the link at the top of the SilverlightSerializer page.
Why is it faster?
So read on if you’d like to know why it’s faster!
SilverlightSerializer is a reflection based serializer. It examines an object to identify the available properties and fields. As anyone who is familiar with .NET will know, reflection isn’t exactly the fastest thing in the world. SS v1 did its level best to cache everything possible, but it still relied on reflection to write and read properties and fields from the underlying objects. This is why SS didn’t perform as well as the inbuilt serializers in .NET.
Now reflection in this case is a hard thing to get around, I don’t know the types in advance and I have no interest in getting the developer to have to write a custom serialization class for each of their types.
The answer to this performance challenge came from using generic classes and using .NET to construct a new generic class on the fly for each property of each class being serialized. The generic class accesses the native property access functions directly, rather than have to use reflection. Fields have to be handled slightly differently, with a reflection function, but at least it’s no slower than the previous method.
First let’s start with the base class that is used for all of the generic classes, it’s called GetSet.
public abstract class GetSet
{
public PropertyInfo Info;
public string Name;
public FieldInfo FieldInfo;
public object Vanilla;
public bool CollectionType;
public abstract object Get(object item);
public abstract void Set(object item, object value);
}
From this base class I create a definition of a generic class, called GetSetGeneric. This class creates Get and Set delegates using the class parameters, these delegates then map to the functions that will be exposed by the property getters and setters on the target class (neat huh). This happens only once per type/property combination and the resulting code is the same speed as writing a function to get the value.
public class GetSetGeneric<T, TR> : GetSet
{
public delegate TR GetValue(T obj);
public delegate void SetValue(T obj, TR value);
private readonly GetValue _get;
private readonly SetValue _set;
public GetSetGeneric(PropertyInfo info)
{
MethodInfo getMethod;
MethodInfo setMethod = null;
Name = info.Name;
Info = info;
CollectionType = Info.PropertyType.GetInterface("IEnumerable", true) != null;
getMethod = info.GetGetMethod();
setMethod = info.GetSetMethod();
_get = (GetValue)Delegate.CreateDelegate(typeof(GetValue), getMethod);
if (setMethod != null) _set = (SetValue)Delegate.CreateDelegate(typeof(SetValue), setMethod);
}
public GetSetGeneric(FieldInfo info)
{
MethodInfo getMethod;
MethodInfo setMethod = null;
Name = info.Name;
FieldInfo = info;
_get = new GetValue(GetFieldValue);
_set = new SetValue(SetFieldValue);
CollectionType = FieldInfo.FieldType.GetInterface("IEnumerable", true) != null;
return;
}
public GetSetGeneric(string name)
{
Name = name;
MethodInfo getMethod;
MethodInfo setMethod= null;
var t = typeof(T);
var p = t.GetProperty(name);
if (p == null)
{
FieldInfo = typeof(T).GetField(Name);
_get = new GetValue(GetFieldValue);
_set = new SetValue(SetFieldValue);
CollectionType = FieldInfo.FieldType.GetInterface("IEnumerable", true) != null;
return;
}
Info = p;
CollectionType = Info.PropertyType.GetInterface("IEnumerable", true) != null;
getMethod = p.GetGetMethod();
setMethod = p.GetSetMethod();
_get = (GetValue)Delegate.CreateDelegate(typeof(GetValue), getMethod);
if(setMethod != null) _set = (SetValue)Delegate.CreateDelegate(typeof(SetValue), setMethod);
}
private TR GetFieldValue(T obj)
{
return (TR)FieldInfo.GetValue(obj);
}
private void SetFieldValue(T obj, TR value)
{
FieldInfo.SetValue(obj, value);
}
public override object Get(object item)
{
return _get((T)item);
}
public override void Set(object item, object value)
{
_set((T)item, (TR)value);
}
}
Once that’s done it’s just a matter of creating the generic classes. Deserialization does this one property at a time form the input stream:
entryConfiguration = new EntryConfiguration();
var pi = entry.OwningType.GetProperty(entry.Name);
if (pi != null)
{
entryConfiguration.Type = pi.PropertyType;
var gs = typeof(GetSetGeneric<,>);
var tp = gs.MakeGenericType(new Type[] { entry.OwningType, pi.PropertyType });
entryConfiguration.Setter = (GetSet)Activator.CreateInstance(tp, new object[] { pi });
}
else
{
var fi = entry.OwningType.GetField(entry.Name);
if (fi != null)
{
entryConfiguration.Type = fi.FieldType;
var gs = typeof(GetSetGeneric<,>);
var tp = gs.MakeGenericType(new Type[] { entry.OwningType, fi.FieldType });
entryConfiguration.Setter = (GetSet)Activator.CreateInstance(tp, new object[] { fi });
}
}
Here you can see I get either the property or the field information, use the type of the containing class and the property in a call to MakeGenericType to construct the correct class, then create an instance of that class that can be used to get and set properties on the object.
Serialization works by creating a list of getters and setters for every sensible property on the object, in SilverlightSerializer that creates a few different flavours depending on whether you are using Checksums etc. If you want to see how I do that, have a look at the GetWriteableAttributes class and the GetAccessors() function.
Wordle Style Word Cloud or Tag Cloud Component For Silverlight
Posted by whydoidoit in Project With Code on July 28, 2011
LATEST VERSION AND DOCUMENTATION AVAILABLE HERE
I’ve been looking for a component that could show Wordle style word clouds. The only Silverlight component I could find was Infragistics xamTagCloud, but it really didn’t produce the output I was looking for. What I wanted was to be able to put lower importance words within the spaces left around larger entries.
Having looked around the web I couldn’t find a component to buy or borrow so I decided to write my own.
I came across this post on Stack Overflow that had a response from the author of Wordle (Jonathan Feinberg), giving some tips on how Wordle works. I used that and the extra reference Jonathan provided to build my component.
The key to word layout is to use a spiral (or another progressive positioning equation) to try to position words, every new word needs to be checked against the previously placed items to ensure that there is no overlap.
As collision is the expensvie part of the algorithm Jonathan suggests using a variety of techniques around collision rectangles and space partitioning to do the item testing; I felt this wasn’t necessary for my needs so I actually test the overlapping pixels to see if there is a hit. This seems to give good enough performance, and if I wanted to improve it I would advocate making a second collision map at a lower resolution (1/8 scale) that would significantly cut down on the processing – but again, wasn’t necessary for me.
If you want to use something to layout instead of my spiral, you need to replace the GetSpiralPoint function with something that will return a progressive space based on an increaseing angle measured in radians.
The component also supports word hit testing and selection as well as coloring words based on a value as well as sizing them.
You can download the full source code for the component and the test project which will allow you to play with the parameters from the link at the top of this post.
Automatic Grid Layout for Silverlight
Posted by whydoidoit in Project With Code on October 6, 2010
I always find myself cursing Grids in Silverlight when I have to go back and insert something else into the layout after the fact: I always forget to move somethings Row and end up with a lot of obscured components. To compensate for this I’ve written a Grid subclass that can automatically layout its children and fill out the ColumnDefinition and RowDefinition for missing values when the children refer to rows and columns beyond the specified dimensions. In addition it will auto layout for multiple columns using sequential children, this is good if all you want is a 2 by n grid of label/editor cells.
My AutoGrid will allow you to define Rows and Columns like an ordinary grid, but if you don’t catch all of the cases then it fills out the rest for you. For instance you could just define the columns and it will fill out the rows based on the Grid.Row settings of the children. If you want to go a step further, then don’t specify any Grid.Row or Grid.Column attributes and instead add a Columns=”x” to the AutoGrid and it will sequentially lay out the children in column then row order.
Normally the rows and columns added are “Auto” sized, you can however set the last row and column to be “*” sized using the properties AutoSizeLastColumn and AutoSizeLastRow. If you need more complex arrangements than this then you should define the items you need sizing explicity using the ColumnDefinitions and/or RowDefinitions attributes.
It really saves me a lot of time when I’m editing this stuff!
Here is an example in full automatic layout mode:
<AutoGrid:AutoGrid x:Name="LayoutRoot" Columns="2">
<TextBlock Text="Name"
Margin="2"/>
<TextBox Components:SelectOnFocus.SelectAll="True" Text="{Binding Name, Mode=TwoWay}"
Margin="2"
Width="150"
/>
<TextBlock Text="Type"
Margin="2"
/>
<ComboBox
ItemsSource="{Binding Type, Converter={StaticResource EnumSource}}"
SelectedItem="{Binding Type, Converter={StaticResource EnumValue}}"
Margin="2"
Width="150"
/>
<TextBlock Text="Width" Margin="2" />
<TextBox Text="{Binding Width, Mode=TwoWay}"
Components:SelectOnFocus.SelectAll="True"
Margin="2"
Width="150"/>
<TextBlock Text="Choice List " VerticalAlignment="Top" Margin="2"/>
<TextBox Width="150"
Height="100"
Margin="2"
AcceptsReturn="True"
Text="{Binding ChoiceList, Converter={StaticResource ListToString}, Mode=TwoWay}"/>
</AutoGrid:AutoGrid>
Which produces this output:
You can download the project from here.
Silverlight VisualState changes using DataBinding not code behind
Posted by whydoidoit in Project With Code on September 9, 2010

I hate the fact that I have to keep using code behind to trigger VisualState changes in my view. Frequently I just want to change a visual state of a control based on the properties of the object to which the control is bound – such as making additional options visible or invisible, changing the mode of the display based on information stored in the model etc.
So I’ve come up with a control that helps! The VisualStateController can be placed in the XAML for a control and be bound to a property of the databound object using its StateMode dependency property.
- If the property is a bool then two further properties OnState and OffState are used to determine the visual state of the control based on the value of the property.
- If the property is an enum then the visual state will be set the the text string name of the enum value.
- If the property is a string it will be used to directly set the visual state
Now changes causing normal binding updates will automatically trigger the visual state changes.
<VisualStateCtrls:VisualStateController StateMode="{Binding IsSelected}"
OnState="Selected"
OffState="Unselected"/>
<VisualStateCtrls:VisualStateController StateMode="{Binding IsResizable}"
OnState="Sizers"
OffState="NoSizers"/>
The VisualStateController binds automatically to the UserControl (or Control) that it is a child of. You can put it inside any panel within the body of your UserControl’s XAML.
You can find the project and source code here.
If you want to achieve the same thing using triggers and a slightly more wordy approach, you can use blend and triggers – see here for details.
Silverlight AllChildren: find all of the visual children of a FrameworkElement
Posted by whydoidoit in Uncategorized on September 2, 2010
Our application has some occasions where we need to iterate the entire child tree of a visual component. Not a common thing in many applications, I use it to pass visual states to the sub elements of a tree, but if you need a routine for this purpose then I thought I would post mine here:
public static List<T> AllChildren<T>(this FrameworkElement ele, Func<DependencyObject, bool> whereFunc = null) where T : class
{
if (ele == null)
return null;
var output = new List<T>();
var c = VisualTreeHelper.GetChildrenCount(ele);
for (var i = 0; i < c; i++)
{
var ch = VisualTreeHelper.GetChild(ele, i);
if (whereFunc != null)
{
if (!whereFunc(ch))
{
continue;
}
}
if ((ch is T))
output.Add(ch as T);
if (!(ch is FrameworkElement))
continue;
output.AddRange((ch as FrameworkElement).AllChildren<T>(whereFunc));
}
return output;
}
The function is an extension method that uses the generic Type to decide on the types of children to return. It takes an optional “Where function” that can be used to stop iterating down branches of the visual tree – please note that the Where function doesn’t only get passed the Type components, it gets everything so you can stop the recursive operation when you want to. If you don’t pass the Where parameter then all visual children are returned.
foreach (var c in panel.AllChildren<Control>((child) => !(child is FdTreeViewItem)))
{
VisualStateManager.GoToState(c, "FlowSelected", true);
}
Debugging Silverlight “element is already the child of another element”!
Posted by whydoidoit in Project With Code on August 30, 2010
The problem
I know how many people are having a problem with the catch-all XAML error “Element is already the child of another element” – it’s been a popular post on this blog and I come across it all of the time. The real problem is that the exception gives no indication of the area causing the failure, you are forced into playing with the source file and banging your head against the wall. Well, help is at hand!
I have written a program that helps identify which part of the XAML is going wrong and tells you about it! Now one caveat – it can only tightly identify a single error that is causing this problem – if more than one thing throws the exception then the best you can hope for is for it to point out the XAML container that contains the code that is failing – such as VisualStateManager. In most cases it will be more specific, because only one element will have changed and cause the exception to be thrown. This ability is helping me a lot, hopefully it can help you too…
The solution
So here’s what I have done. I have written a XAML validator that reads in the file and then attempts to process it. When the file has a problem it starts to prune out nodes in the XAML one XML node at a time (I mean it puts back nodes that didn’t solve the problem and tries the next in sequence). It does this starting with the nodes that have no children, then the ones with 1, 2 and so on, until it has to remove the entire body – hopefully the error is found long before this. Using this technique the algorithm tries to give you the most tightly isolated area of the XAML to focus on.
When it identifies a node, it checks whether removing any attribute helps and returns this in addition to the offending XAML if it resolves the issue.
The result is a string describing the XAML and any offending attribute.
This is a debugging tool only – it really slows down the application using it, so don’t call it when you don’t have a problem - but it massively improves your debugging time. I normally instantiate in the constructor of the failing class and Debug.WriteLine() its result. It is VITAL that you call it from the assembly that contains the failing XAML – it won’t work if you don’t. (See the discussion below if you want to know why!)
You can download the project from here. Feel free to use it as you see fit.
Here’s an example of using it:
public HtmlTextBox()
{
var s = ValidateXaml.GetXamlErrors(new System.Uri("/Alchemy.extension;component/Components/HtmlTextBox.xaml", System.UriKind.Relative));
Debug.WriteLine(s);
InitializeComponent();
}
Caveats
This isn’t going to work too well if removing a node that fails just causes the problem to propagate to a part of the XAML that was previously valid - the only way I can think about solving that requires far more recursion and taking out multiple nodes at each level. I’d be interested in anyone elses view on this and any other strategies…
You may have a problem with project references, if you do then see the discussion below, hopefully I’ve accounted for most circumstances.
Discussion
Having had the initial idea about this approach I ran into a couple of stumbling blocks which are worth exploring for those who are interested.
Firstly, when you call InitializeComponent in a UserControl etc – it uses Application.LoadComponent to parse the XAML. I can’t use that approach because it takes a URI and I need to pass in a string which is the XAML with an element removed. For this reason my code uses XamlReader to parse the file – the problem there is that it always throws an exception for XAML that contains an x:Class attribute. My first job then is to strip that out.
The next attribute problem was much harder to solve. UserControl xmlns attributes are used to provide reference to components stored in other assemblies. The attribute provides the namespace and the assembly. The assembly is omitted for other controls that are contained in the same assembly as the problem control. LoadComponent has no problems with resolving this reference, but XamlReader throws our favorite exception if it isn’t there – this took me a LONG time to figure out.
So I have to add an “assembly=” extension to the xmlns references that don’t contain one (except the xlmns:x) to ensure that XamlReader will parse a correct file. I do this by enquiring about the calling assembly and adding its name to the attribute.
Sounds sensible right? Well it was a bit more complicated than that – if I just modify the attribute while it is connected to the document, some behind the scenes magic changes all of the things that are referred to by that namespace! Guess what the error is? Yep, “element is already the child of another element” :)
So now I remove the attribute from the document, modify it and put it back – presto! No unwanted changes and the algorithm finally gets to have a go at parsing the file.
If this attribute modification causes you a problem, you could remove the code and explicitly qualify your project references, this does work, I’ve tried it and would account for a situation in which I accidentally update an xmlns that doesn’t need touching – but this does mean that you won’t be using the VS2010 automatically generated references. I hope that this won’t normally be a problem.
UPDATE: I’ve modified the source to allow you to pass a parameter that turns off the xmlns modifications – see above comment about explicit assembly references if you set this. It defaults to “true” which enables the automatic update of references.
ProportionalPanel for Silverlight
Posted by whydoidoit in Project With Code on July 19, 2010
I wanted a panel that distributes its children according to the proportion of their width or by a proportion supplied by the object attached to the DataContext. This lead to me writing PropotionalPanel – the first custom panel I have written. It’s useful in building dashboards and other layouts that require collections of children, because Grids aren’t easy to use inside ItemsControls. I wrote this control to be used as the ItemsPanel of a list box and it works well in that context.When writing a panel the two important routines are MeasureOverride and ArrangeOverride. There’s lots of documentation on these in the help, but it’s interesting to see the parameters with which these methods are called at different times.
For instance, even if you have a fixed size container, MeasureOverride is called with infinite dimensions on the first occasion, thereafter the call specifies the fixed size.
Here’s my version of the MeasureOverride routine. I maintain a variable called totalProportion which is either the sum of the proportions of the attached objects, or the sum of the proportions of the stretched dimension based on orientation.
protected override Size MeasureOverride(Size availableSize)
{
Size finalSize = new Size(availableSize.Width, availableSize.Height);
double totalProportion = 0;
foreach (var c in Children.OfType<FrameworkElement>())
{
if (c.DataContext is IProportional)
{
totalProportion += (c.DataContext as IProportional).GetProportion();
}
else
{
totalProportion += Orientation == Orientation.Vertical
? c.DesiredSize.Height
: c.DesiredSize.Width;
}
}
double sizeAvailable, maxAlternate = 0;
switch (Orientation)
{
case Orientation.Horizontal:
sizeAvailable = availableSize.Width;
if (double.IsNaN(sizeAvailable) || double.IsPositiveInfinity(sizeAvailable))
{
sizeAvailable = 0;
foreach (var c in Children)
{
c.Measure(availableSize);
sizeAvailable += c.DesiredSize.Width;
maxAlternate = Math.Max(maxAlternate, c.DesiredSize.Height);
}
finalSize.Width = sizeAvailable;
finalSize.Height = maxAlternate;
}
else
{
foreach (var c in Children.OfType<FrameworkElement>())
{
double p;
if (c.DataContext is IProportional)
{
p = (c.DataContext as IProportional).GetProportion();
}
else
{
p = Orientation == Orientation.Vertical
? c.DesiredSize.Height
: c.DesiredSize.Width;
}
c.Measure(new Size(Math.Max(0,Math.Floor((sizeAvailable * p)/totalProportion)), finalSize.Height));
}
}
break;
case Orientation.Vertical:
sizeAvailable = availableSize.Height;
if (double.IsNaN(sizeAvailable) || double.IsPositiveInfinity(sizeAvailable))
{
sizeAvailable = 0;
foreach (var c in Children)
{
c.Measure(availableSize);
sizeAvailable += c.DesiredSize.Height;
maxAlternate = Math.Max(maxAlternate, c.DesiredSize.Width);
}
finalSize.Height = sizeAvailable;
finalSize.Width = maxAlternate;
}
else
{
foreach (var c in Children.OfType<FrameworkElement>())
{
double p;
if (c.DataContext is IProportional)
{
p = (c.DataContext as IProportional).GetProportion();
}
else
{
p = Orientation == Orientation.Vertical
? c.DesiredSize.Height
: c.DesiredSize.Width;
}
c.Measure(new Size(finalSize.Width, Math.Max(0, Math.Floor((sizeAvailable * p) / totalProportion))));
}
}
break;
}
return finalSize;
}
}
First the total proportion is calculated by walking through the children and summing either the proportions from the attached object, or the required size.
double totalProportion = 0;
foreach (var c in Children.OfType<FrameworkElement>())
{
if (c.DataContext is IProportional)
{
totalProportion += (c.DataContext as IProportional).GetProportion();
}
else
{
totalProportion += Orientation == Orientation.Vertical
? c.DesiredSize.Height
: c.DesiredSize.Width;
}
}
If the parameters of the MeasureOverride call have infinite dimensions I need to measure all of the children for their desired size, if there is a specific size then I need to measure each child providing guidance on how much space they will be allocated.
case Orientation.Horizontal:
sizeAvailable = availableSize.Width;
if (double.IsNaN(sizeAvailable) || double.IsPositiveInfinity(sizeAvailable))
{
sizeAvailable = 0;
foreach (var c in Children)
{
c.Measure(availableSize);
sizeAvailable += c.DesiredSize.Width;
maxAlternate = Math.Max(maxAlternate, c.DesiredSize.Height);
}
finalSize.Width = sizeAvailable;
finalSize.Height = maxAlternate;
}
else
{
foreach (var c in Children.OfType<FrameworkElement>())
{
double p;
if (c.DataContext is IProportional)
{
p = (c.DataContext as IProportional).GetProportion();
}
else
{
p = Orientation == Orientation.Vertical
? c.DesiredSize.Height
: c.DesiredSize.Width;
}
c.Measure(new Size(Math.Max(0,Math.Floor((sizeAvailable * p)/totalProportion)), finalSize.Height));
}
}
break;
In the fixed size measurement I use the proportion to calculate the amount of stretched space available to the control. It is vital that you both measure and arrange children in the correct size – if you don’t measure then it initially appears to work, but strange sizing artefacts occur.
The arrangement pass is very similar to the fixed size measurement, except you pass a rectangle to the child giving it the layout slot into which it will fit:
if (Orientation == Orientation.Vertical)
{
foreach (var c in Children.OfType<FrameworkElement>())
{
double p = 0;
if (c.DataContext is IProportional)
{
p = (c.DataContext as IProportional).GetProportion();
}
else
{
p = c.DesiredSize.Height;
}
double d = Math.Max(0,Math.Floor((finalSize.Height * p) / totalProportion));
c.Arrange(new Rect(0, offset, finalSize.Width, d));
offset += d;
}
}
The IProportional interface is implemented on objects that are used as DataContexts for the items in my panel:
public interface IProportional
{
double GetProportion();
}
When you have a proportional panel like this it’s a good idea to provide some way for the user to resize things! I use a thing called FrameControl in my ListBox’s DataTemplate – this provides sizing thumbs that can change the horizontal and vertical proportions of the underlying DataContext objects.
private void WidthThumb_OnDragDelta(object sender, DragDeltaEventArgs e)
{
var pp = this.FirstVisualAncestorOfType<ProportionalPanel>();
var thisIndex = pp.Children.IndexOf(this.FirstVisualAncestorOfType<ListBoxItem>());
var thisItem = DataContext as DashboardItem;
var nextItem = pp.Children[thisIndex + 1].Cast<FrameworkElement>().DataContext as DashboardItem;
Debug.Assert(thisItem != null);
Debug.Assert(nextItem != null);
var move = (e.HorizontalChange * GetProportions()) / pp.ActualWidth;
if (thisItem.Proportion + move < 0)
move = - thisItem.Proportion;
if (nextItem.Proportion - move < 0)
move = nextItem.Proportion;
thisItem.Proportion += move;
nextItem.Proportion -= move;
pp.InvalidateMeasure();
}
This example uses my FirstVisualAncestorOfType extension method found elsewhere on this blog. For the FrameControl it finds the ProportionalPanel that owns it then works out what the pixel change in the Thumb means in terms of the change to the arbitrary proportions returning by the IProportional implementation. If you just used heights then this would be a lot simpler, but harder to store. Obviously you need a thumb for the sizable dimension, but not both, so I show just the relevant thumb based on the panel’s orientation.
To build a dashboard I layer panel within panel as you can see in this video – which also shows the thumb action and the ability to react to drag and drop (not allowing containers of the same type to be embedded within containers).
Here’s the complete code for the panel. I have the IProportional interface defined in a library that is used by the items I attach to the DataContext, so that they don’t have to reference the Panel - but you might just want to insert it in this namespace.
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace DashboardRenderers
{
public class ProportionalPanel : Panel
{
public Orientation Orientation
{
get
{
return (Orientation)GetValue(OrientationProperty);
}
set
{
SetValue(OrientationProperty, value);
}
}
// Using a DependencyProperty as the backing store for Orientation. This enables animation, styling, binding, etc...
public static readonly DependencyProperty OrientationProperty =
DependencyProperty.Register("Orientation", typeof(Orientation), typeof(ProportionalPanel), new PropertyMetadata(System.Windows.Controls.Orientation.Vertical));
protected override Size ArrangeOverride(Size finalSize)
{
double offset = 0;
double totalProportion = 0;
foreach (var c in Children.OfType<FrameworkElement>())
{
if (c.DataContext is IProportional)
{
totalProportion += (c.DataContext as IProportional).GetProportion();
}
else
{
totalProportion += Orientation == Orientation.Vertical
? c.DesiredSize.Height
: c.DesiredSize.Width;
}
}
if (Orientation == Orientation.Vertical)
{
foreach (var c in Children.OfType<FrameworkElement>())
{
double p = 0;
if (c.DataContext is IProportional)
{
p = (c.DataContext as IProportional).GetProportion();
}
else
{
p = c.DesiredSize.Height;
}
double d = Math.Max(0,Math.Floor((finalSize.Height * p) / totalProportion));
c.Arrange(new Rect(0, offset, finalSize.Width, d));
offset += d;
}
}
else
{
foreach (var c in Children.OfType<FrameworkElement>())
{
double p = 0;
if (c.DataContext is IProportional)
{
p = (c.DataContext as IProportional).GetProportion();
}
else
{
p = c.DesiredSize.Width;
}
double d = Math.Max(0, Math.Floor((finalSize.Width * p) / totalProportion));
c.Arrange(new Rect(offset, 0, d, finalSize.Height));
offset += d;
}
}
return finalSize;
}
protected override Size MeasureOverride(Size availableSize)
{
Size finalSize = new Size(availableSize.Width, availableSize.Height);
double totalProportion = 0;
foreach (var c in Children.OfType<FrameworkElement>())
{
if (c.DataContext is IProportional)
{
totalProportion += (c.DataContext as IProportional).GetProportion();
}
else
{
totalProportion += Orientation == Orientation.Vertical
? c.DesiredSize.Height
: c.DesiredSize.Width;
}
}
double sizeAvailable, maxAlternate = 0;
switch (Orientation)
{
case Orientation.Horizontal:
sizeAvailable = availableSize.Width;
if (double.IsNaN(sizeAvailable) || double.IsPositiveInfinity(sizeAvailable))
{
sizeAvailable = 0;
foreach (var c in Children)
{
c.Measure(availableSize);
sizeAvailable += c.DesiredSize.Width;
maxAlternate = Math.Max(maxAlternate, c.DesiredSize.Height);
}
finalSize.Width = sizeAvailable;
finalSize.Height = maxAlternate;
}
else
{
foreach (var c in Children.OfType<FrameworkElement>())
{
double p;
if (c.DataContext is IProportional)
{
p = (c.DataContext as IProportional).GetProportion();
}
else
{
p = Orientation == Orientation.Vertical
? c.DesiredSize.Height
: c.DesiredSize.Width;
}
c.Measure(new Size(Math.Max(0,Math.Floor((sizeAvailable * p)/totalProportion)), finalSize.Height));
}
}
break;
case Orientation.Vertical:
sizeAvailable = availableSize.Height;
if (double.IsNaN(sizeAvailable) || double.IsPositiveInfinity(sizeAvailable))
{
sizeAvailable = 0;
foreach (var c in Children)
{
c.Measure(availableSize);
sizeAvailable += c.DesiredSize.Height;
maxAlternate = Math.Max(maxAlternate, c.DesiredSize.Width);
}
finalSize.Height = sizeAvailable;
finalSize.Width = maxAlternate;
}
else
{
foreach (var c in Children.OfType<FrameworkElement>())
{
double p;
if (c.DataContext is IProportional)
{
p = (c.DataContext as IProportional).GetProportion();
}
else
{
p = Orientation == Orientation.Vertical
? c.DesiredSize.Height
: c.DesiredSize.Width;
}
c.Measure(new Size(finalSize.Width, Math.Max(0, Math.Floor((sizeAvailable * p) / totalProportion))));
}
}
break;
}
return finalSize;
}
}
}
Finding a typed visual parent in Silverlight
Posted by whydoidoit in Project With Code on July 17, 2010
My application frequently needs to find a parent of a Silverlight element, and due to the nature of popup panels I also sometimes want to know if the element is “logically” connected to another element. To achieve this I wrote a couple of helper functions that walk the visual tree and return a typed parent. You can implement a special interface to indicate that there is a logical connection between items that aren’t physically connected to each other in the Visual Tree too if you need to (very helpful with focus issues).
public static T FirstVisualAncestorOfType<T>(this DependencyObject element) where T : DependencyObject
{
if (element == null) return null;
var parent = VisualTreeHelper.GetParent(element) as DependencyObject;
while (parent != null)
{
if (parent is T)
return (T)parent;
if (parent is IBreakVisualParenting)
{
parent = ((IBreakVisualParenting)parent).Parent;
}
else
parent = VisualTreeHelper.GetParent(parent) as DependencyObject;
}
return null;
}
public interface IBreakVisualParenting
{
DependencyObject Parent { get; }
}
public static T LastVisualAncestorOfType<T>(this DependencyObject element) where T : DependencyObject
{
T item = null;
var parent = VisualTreeHelper.GetParent(element) as DependencyObject;
while (parent != null)
{
if (parent is T)
item = (T) parent;
if(parent is IBreakVisualParenting)
{
parent = ((IBreakVisualParenting) parent).Parent;
}
else
parent = VisualTreeHelper.GetParent(parent) as DependencyObject;
}
return item;
}
IsInVisualTree – helper function for determining if a Silverlight item is visible or in the visual tree
Posted by whydoidoit in Project With Code on July 17, 2010
Some Silverlight functions, especially those to do with coordinate transforms, tend to throw exceptions if the item you are testing isn’t in the visual tree and it is often interesting to know if an item is presently going to be displayed or not. The following code uses the standard way of determining this, by walking the visual tree to see if the item is connected to the root visual of the application. Being in the visual tree doesn’t mean the item is actually visible, this depends on the collapsed state of the element and its parents.
/// <summary>
/// Determines if an element is in the visual tree
/// </summary>
/// <param name="element">The element.</param>
/// <returns>
/// <c>true</c> if element parameter is in
/// visual tree otherwise, <c>false</c>.
/// </returns>
public static bool IsInVisualTree(this DependencyObject element)
{
return IsInVisualTree(element, Application.Current.RootVisual as DependencyObject);
}
public static bool IsInVisualTree(this DependencyObject element, DependencyObject ancestor)
{
DependencyObject fe = element;
while (fe != null)
{
if (fe == ancestor)
{
return true;
}
fe = VisualTreeHelper.GetParent(fe) as DependencyObject;
}
return false;
}
To test if an item is visible you just walk the parents and check the Visibility state:
public static bool IsVisible(this FrameworkElement ele, FrameworkElement topParent=null)
{
if (!ele.IsInVisualTree()) return false;
while(ele != topParent && ele != null)
{
if (ele.Visibility == Visibility.Collapsed) return false;
ele = VisualTreeHelper.GetParent(ele) as FrameworkElement;
}
return true;
}
Silverlight Flip Control – page flipping without the performance problems
Posted by whydoidoit in Project With Code on June 26, 2010
A while ago I was blogging about the flip control that I had written for Silverlight. My first attempt at this used basic transitions only to show two sides of a page, but I found this slowed down dramatically when the contents of each side were complex. The answer was to take an image of the contents of each side at the moment of the flip occuring and animate that instead, in this way it’s always smooth no matter how many controls are being used.
I’m posting the code for the control here. As usual feel free to use or modify it in any way you like, I’d appreciate any really interesting upgrades be sent back to me so I can include them here. There’s a sample project and web site in the ZIP file too.
The flip control is pretty straight forward. It has two sides called Page1 and Page2. The property used to flip over the control is Page2Visible, which is a bool. There’s a PageChanged event that fires if you need the notificaton. There are also advanced properties for horizontal and vertical alignment separate for each side (Side1VerticalAlignment etc).
If you are looking through the code then it’s CreateImages that does most of the hard work. This routine takes an image of each of the pages and swops those for the real content during the flip. The images are reset when the Visual State Manager says the transition is complete.
Element is already the child of another element – Arghhhhhh
Posted by whydoidoit in Programming on June 25, 2010
Sometimes I just hate Silverlight. Spent 5 hours debugging a problem that resulted in the “Element is already the child of another element” InvalidOperation exception. I looked at everything; looked to see if I was accidentally reparenting something: no. Looked for unexpected recursion: no. Played with every debugger setting to get more information and finally disected the application – all to no avail.
Then I noticed I’d commented out an Image in one of my templates (derived from a Telerik template for tree nodes) and happened to notice that it was the target of a Storyboard. Yep that was it – not an error that reads “You’ve targeted an element that doesn’t exist” oh no. “Element is already the child of another element” – like hell it was
So word to the wise, if you don’t think you are actually making an element the child of another element, look for any inconsistencies in your storyboards and animations.
Help is at hand:
Since writing this post I’ve come up with an algorithm to help identify XAML markup that causes this exception. The post here has a link to the project and a description of the approach.






Mike Talbot is Chief Visionary of 3radical. He started his career as a game programmer working for UbiSoft and Electronic Arts among others. Currently he is programming mobile applications in Javascript, HTML5 and ASP.NET.
email: 