Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
swdev:dotnet:wpf:datatemplates [2012/12/07 17:10]
smayr [How to: Find DataTemplate-Generated Elements]
swdev:dotnet:wpf:datatemplates [2012/12/07 17:15] (current)
smayr [Example 2]
Line 83: Line 83:
 Source: [[http://msdn.microsoft.com/en-us/library/system.windows.frameworktemplate.findname.aspx|MSDN: FrameworkTemplate.FindName Method]]    Source: [[http://msdn.microsoft.com/en-us/library/system.windows.frameworktemplate.findname.aspx|MSDN: FrameworkTemplate.FindName Method]]   
  
 +=== Example 1 ===
 For a ListBoxItem: For a ListBoxItem:
 <code xml> <code xml>
Line 99: Line 100:
 ComboBox cb = (ComboBox)listBox.ItemTemplate.FindName("IconComboBox", lbi); ComboBox cb = (ComboBox)listBox.ItemTemplate.FindName("IconComboBox", lbi);
 </code>   </code>  
 +
 +=== Example 2 ===
 +For a ListBoxItem:
 +<code xml>
 +<Window.Resources>
 +    <local:GreekGods x:Key="greekGods"/>
 +    <DataTemplate x:Key="itemTemplate">
 +        <TextBlock Text="{Binding Path=Name}" />
 +    </DataTemplate>
 +</Window.Resources>
 +. . .    
 +<ListBox ItemsSource="{StaticResource greekGods}" ItemTemplate="{StaticResource itemTemplate}" Name="listBox"/>
 +</code>
 +
 +<code csharp>
 +// To get GreekGod object
 +GreekGod greekGod = (GreekGod)(listBox.Items[0]);
 +
 +// To get ListBoxItem container holding object GreekGod
 +ListBoxItem lbi1 = (ListBoxItem)(listBox.ItemContainerGenerator.ContainerFromIndex(0));
 +ListBoxItem lbi2 = (ListBoxItem)(listBox.ItemContainerGenerator.ContainerFromItem(listBox.Items.CurrentItem));
 +</code>  
 +
 +Source: [[http://www.zagstudio.com/blog/7#.UMESToM72dI|ZAG Log: How to get a ListBoxItem from a data bound ListBox]]