Linq to Xaml (Linq to VisualTree)

January 9th, 2011 Categories: Uncategorized

I had a problem converting the xaml for custom control, that needed some parent for internal calculations. Parent reference was exposed as a dependency property and xaml used relative search up:

 
<s:Connector
DraggingCanvas="{Binding RelativeSource={RelativeSource AncestorType=Canvas, AncestorLevel=2}}" />

Its ok in WPF but SL4 does not allow anything but TemplatedParent or Self in RelativeSource. I was driven to switch to code and obtain the reference in code. Having multiple utilities for search ancestors, did not help me a lot: All I need was topmost ancestor having specified DataContext. Google gave me a cool reference to people doing Linq2VisualTree: Having slightly adapted, my code become very clear:

var parentScreen = this.Ancestors<FrameworkElement>().Last(d => d.DataContext is Screen);

Colin, Thanks a lot for your excellent library!

Tags: ,
No comments yet.

Leave a Comment