I was recently confronted with a scenario in witch a xaml element needed to be dynamically replaced and nested in a container control. There’s nothing unusual about this except for the fact that when this happens the element being replaced might have attached dependency properties set on it. Needless to say that in this scenario such operation might have significant impact. Imagine if your element is inside a Canvas panel and has some of its attached properties set, like Canvas.Top or Canvas.Left.
My first approach was to go through reflection on the parent and get all DependencyProperties, then invoke GetValue() on the element for each one. It worked but it got me thinking that there had to be a cleaner way, since Attached Property values collection is internal and not directly accessible. Then I got to know a primitive called MarkupWriter. In fact, I’ve crossed with it before on a previous project but never got to actually use it. This time around I’ll make it official, so I’m sharing a little snippet that checks an element for Attached Properties, followed by an example:
public static IDictionary GetAttachedProperties(DependencyObject element)
{
var attachedPropertyList = new Dictionary();
var markupObject = MarkupWriter.GetMarkupObjectFor(element);
foreach (var prop in markupObject.Properties)
{
if (prop.IsAttached)
attachedPropertyList.Add(prop.DependencyProperty, prop.Value);
}
return attachedPropertyList;
}
Here’s a simple usage example:
var border = new Border()
{
Width = 200, Height = 200,
BorderBrush = Brushes.Blue,
BorderThickness = new Thickness(1)
};
border.SetValue(Canvas.TopProperty, 10d);
border.SetValue(Canvas.LeftProperty, 50d);
var list = GetAttachedProperties(border);
// Beware that ForEach is a Unity enumerable extension.
list.ForEach(prop => Console.WriteLine("Attached property Name: {0}", prop));
/*
Outputs:
Attached property Name: [Left, 50]
Attached property Name: [Top, 10]
*/
Hope it helps.
















1 comment so far
Ran a thousand laps for that and you killed it in a handful of lines. Better late than ever I guess…
March 25th, 2010Add a comment