This is a mirror of official site: http://jasper-net.blogspot.com/

How to Access a Named Control Inside a XAML DataTemplate (using C#)

| Wednesday, September 12, 2012
Let me summarize the problem
In XAML, the ItemsControl, ListBox, ListView, FlipView, or GridView are the repeater controls. To define how each item is displayed in the UI, the developer defines a DataTemplate which he assigns to the ItemsControl’s ItemTemplate property. The ItemTemplate is like this:


<ItemTemplate>
<DataTemplate>
<TextBox x:Name=”TextBox1” />

So far, so easy. This is a common scenario and necessary for any repeater control in XAML. Rendering the ItemsControl, the ItemTemplate is repeated (see below) for every item in the ItemsSource (which has been assigned to some enumerable value like IList, ObservableCollection or even an Array).

How do you access controls inside a Template?
There is more than one approach. One approach, and my least favorite, is using the Loaded RoutedEvent on the TextBox control itself. In this approach you store the resulting (sender) in some dictionary. The up-side is that this event is handled on the page. The downside is how unmanageable it becomes if there are many objects or many different objects.

Spelunking with the Visual Tree
The preferred approach, to me, is navigating through the visual tree of the  individual item. With this you are effectively changing your scope into the individual item. From there you interact with it like you expect. I realize it’s not as simple as Loaded, but ‘tis far more repeatable, understandable and maintainable, and cleaner. Here’s how you do it:

...
...

Inline image 1

Read more: DZone
QR: Inline image 2

Posted via email from Jasper-net

0 comments: