次の方法で共有


How to access a named control inside a XAML DataTemplate (using CSharp)

imageLet 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:

The ItemTemplate

<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).

Note: It is possible to vary what ItemTemplate is used per-item using the ItemTemplateSelector but for the sake of this example (and simplicity) I’m just talking about the vanilla scenario.

The User Interface

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

So far so good. Your data is displaying. So, what’s the problem? See the name of the TextBox? It’s TextBox1 over and over and over. To make this work, the scope of a template is unique to the page. This means referencing a TextBox inside a DataTemplate by name is impossible. To do so, we must spelunk into the ItemTemplate’s DataTemplate.

How do you access controls inside a Template?

Read the whole article here