{"id":1730,"date":"2012-09-07T20:51:30","date_gmt":"2012-09-08T01:51:30","guid":{"rendered":"http:\/\/www.wiredprairie.us\/blog\/?p=1730"},"modified":"2012-09-07T20:51:30","modified_gmt":"2012-09-08T01:51:30","slug":"how-to-find-an-element-in-a-datatemplate-in-winrtxaml","status":"publish","type":"post","link":"https:\/\/www.wiredprairie.us\/blog\/index.php\/archives\/1730","title":{"rendered":"How to find an element in a DataTemplate in WinRT\/XAML."},"content":{"rendered":"
Here\u2019s one way to find a named element in a DataTemplate in XAML in Windows 8 XAML.<\/p>\n
You might try FindName to discover it doesn\u2019t work. That\u2019s because it\u2019s not recursive.<\/p>\n
So, I created a simple extension method to do the same thing:<\/p>\n
public static class <\/span>FrameworkElementExtensions\n<\/span>{\n <\/span>public static <\/span>FrameworkElement <\/span>FindDescendantByName(<\/span>this <\/span>FrameworkElement <\/span>element, <\/span>string <\/span>name)\n {\n <\/span>if <\/span>(element == <\/span>null <\/span>|| <\/span>string<\/span>.IsNullOrWhiteSpace(name)) { <\/span>return null<\/span>; }\n\n <\/span>if <\/span>(name.Equals(element.Name, <\/span>StringComparison<\/span>.OrdinalIgnoreCase))\n {\n <\/span>return <\/span>element;\n }\n <\/span>var <\/span>childCount = <\/span>VisualTreeHelper<\/span>.GetChildrenCount(element);\n <\/span>for <\/span>(<\/span>int <\/span>i = 0; i < childCount; i++)\n {\n <\/span>var <\/span>result = (<\/span>VisualTreeHelper<\/span>.GetChild(element, i) <\/span>as <\/span>FrameworkElement<\/span>).FindDescendantByName(name);\n <\/span>if <\/span>(result != <\/span>null<\/span>) { <\/span>return <\/span>result; }\n }\n <\/span>return null<\/span>;\n }\n}<\/span><\/pre>\nThe code above loops through the children and attempts to match by name. <\/p>\n
A simple usage (admittedly, this is stupid and clunky as lists are often virtualized, but \u2026)<\/p>\n
private void <\/span>Page_Loaded_1(<\/span>object <\/span>sender, Windows.UI.Xaml.<\/span>RoutedEventArgs <\/span>e)\n{\n <\/span>for <\/span>(<\/span>int <\/span>i = 0; i < myPeeps.Items.Count; i++)\n {\n <\/span>var <\/span>element = myPeeps.ItemContainerGenerator.ContainerFromIndex(i) <\/span>as <\/span>FrameworkElement<\/span>;\n <\/span>if <\/span>(element != <\/span>null<\/span>)\n {\n <\/span>var <\/span>tb = element.FindDescendantByName(<\/span>"tbValue"<\/span>) <\/span>as <\/span>TextBlock<\/span>;\n <\/span>if <\/span>(tb != <\/span>null<\/span>)\n {\n tb.Text = i.ToString();\n }\n }\n }\n}<\/span><\/pre>\nGiven this DataTemplate and Page:<\/p>\n
<<\/span>Page.Resources<\/span>>\n <<\/span>local<\/span>:<\/span>SampleDataSource <\/span>x<\/span>:<\/span>Key<\/span>="sampleData" \/>\n <<\/span>DataTemplate <\/span>x<\/span>:<\/span>Key<\/span>="SampleDataTemplate">\n <<\/span>Grid <\/span>>\n <<\/span>Grid.RowDefinitions<\/span>>\n <<\/span>RowDefinition <\/span>Height<\/span>="Auto"\/>\n <<\/span>RowDefinition <\/span>Height<\/span>="Auto"\/>\n <\/<\/span>Grid.RowDefinitions<\/span>>\n <<\/span>TextBlock <\/span>HorizontalAlignment<\/span>="Left" <\/span>Text<\/span>="{<\/span>Binding <\/span>Name<\/span>}" \/>\n <<\/span>TextBlock <\/span>Grid.Row<\/span>="1" <\/span>Name<\/span>="tbValue" \/>\n <\/<\/span>Grid<\/span>>\n <\/<\/span>DataTemplate<\/span>>\n<\/<\/span>Page.Resources<\/span>>\n\n<<\/span>Grid <\/span>Background<\/span>="{<\/span>StaticResource <\/span>ApplicationPageBackgroundThemeBrush<\/span>}" \n <\/span>DataContext<\/span>="{<\/span>StaticResource <\/span>sampleData<\/span>}">\n <<\/span>ItemsControl <\/span>x<\/span>:<\/span>Name<\/span>="myPeeps"\n <\/span>ItemsSource <\/span>= "{<\/span>Binding <\/span>Persons<\/span>}"\n <\/span>ItemTemplate<\/span>="{<\/span>StaticResource <\/span>SampleDataTemplate<\/span>}" <\/span>FontSize<\/span>="22"\/>\n<\/<\/span>Grid<\/span>><\/span><\/pre>\nAnd this sample data:<\/p>\n
public class <\/span>Person <\/span>{\n <\/span>public string <\/span>Name { <\/span>get<\/span>; <\/span>set<\/span>; } \n} \n\n<\/span>public class <\/span>SampleDataSource <\/span>{\n <\/span>public <\/span>IEnumerable<\/span><<\/span>Person<\/span>> Persons { <\/span>get<\/span>; <\/span>private set<\/span>; }\n \n \n <\/span>public <\/span>SampleDataSource () {\n <\/span>var <\/span>list = <\/span>new <\/span>List<\/span><<\/span>Person<\/span>>();\n \n list.Add(<\/span>new <\/span>Person <\/span>{ Name = <\/span>"Alex" <\/span>});\n list.Add(<\/span>new <\/span>Person <\/span>{ Name = <\/span>"Betsy" <\/span>});\n list.Add(<\/span>new <\/span>Person <\/span>{ Name = <\/span>"Carla" <\/span>});\n list.Add(<\/span>new <\/span>Person <\/span>{ Name = <\/span>"Donald" <\/span>});\n list.Add(<\/span>new <\/span>Person <\/span>{ Name = <\/span>"Erica" <\/span>});\n list.Add(<\/span>new <\/span>Person <\/span>{ Name = <\/span>"Francis" <\/span>}); \n \n <\/span>this<\/span>.Persons = list;\n } \n}<\/span><\/pre>\nYou\u2019ll get results like this:<\/p>\n
<\/p>\n","protected":false},"excerpt":{"rendered":"
Here\u2019s one way to find a named element in a DataTemplate in XAML in Windows 8 XAML. You might try FindName to discover it doesn\u2019t work. That\u2019s because it\u2019s not recursive. So, I created a simple extension method to do the same thing: public static class FrameworkElementExtensions { public static FrameworkElement FindDescendantByName(this FrameworkElement element, string […]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true},"categories":[4],"tags":[82,119,105,107],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/pd5QIe-rU","jetpack_likes_enabled":true,"jetpack-related-posts":[{"id":1705,"url":"https:\/\/www.wiredprairie.us\/blog\/index.php\/archives\/1705","url_meta":{"origin":1730,"position":0},"title":"WinRT\/Xaml\/AKA Metro DataTemplate selection based on Data Types","date":"August 20, 2012","format":false,"excerpt":"You may have noticed that WinRT does not have automatic resolution of a DataTemplate based on the data type of object added to an ItemsControl. While unfortunate as this behavior is quite handy, it\u2019s not too difficult to replicate the functionality using a DataTemplateSelector. WPF for example, could do something\u2026","rel":"","context":"In "Coding"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":568,"url":"https:\/\/www.wiredprairie.us\/blog\/index.php\/archives\/568","url_meta":{"origin":1730,"position":1},"title":"Data Binding and Tooltips in Silverlight","date":"September 19, 2008","format":false,"excerpt":"Have you ever wanted to databind a tooltip in Silverlight (or WPF for that matter), and found that the DataContext isn't available for tooltips (the datacontext is null)? It's very annoying. Tooltips, unfortunately, aren't connected to their parents in anyway when they're created, so they loose the ability to connect\u2026","rel":"","context":"In "Coding"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1701,"url":"https:\/\/www.wiredprairie.us\/blog\/index.php\/archives\/1701","url_meta":{"origin":1730,"position":2},"title":"Windows 8 WinRT\/Metro Missing UpdateSourceTrigger","date":"August 5, 2012","format":false,"excerpt":"If you\u2019ve done WPF or Silverlight programming, you may have found an occasion where using the Binding property UpdateSourceTrigger set to PropertyChanged was extremely useful. (I know I have!) It may have looked something like this: The key feature was the live updating of the\u2026","rel":"","context":"In "Coding"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":388,"url":"https:\/\/www.wiredprairie.us\/blog\/index.php\/archives\/388","url_meta":{"origin":1730,"position":3},"title":"Silverlight Weather Demonstration","date":"June 26, 2008","format":false,"excerpt":"Demonstration available here. (You'll need to wait for a moment while it loads the first time). I've created a reasonably simple, yet multi-technology (and discipline) demonstration using Silverlight for the user interface and ASP.NET as the back-end. The demonstration uses: Silverlight 2.0 Data binding Delayed downloading of images \"Web services\"\u2026","rel":"","context":"In "Coding"","img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.wiredprairie.us\/blog\/wp-content\/uploads\/2008\/06\/image21.png?resize=350%2C200","width":350,"height":200},"classes":[]},{"id":670,"url":"https:\/\/www.wiredprairie.us\/blog\/index.php\/archives\/670","url_meta":{"origin":1730,"position":4},"title":"Silverlight: Dynamically creating XAML elements at runtime","date":"January 19, 2009","format":false,"excerpt":"Given the following XML file: