I have a list of strings displayed by a Silverlight ItemsControl. The DataTemplate is a Border control with a TextBlock as its child. How can I access the border control corresponding to an item? For example, I might want to do this to change the background color.
A:
You can override the ItemsControl.GetContainerForItemOverride method and save the object-container pairs in a dictionary.
jarda
2008-11-12 13:49:16
+2
A:
An easier way to do this is to grab the Parent of the textblock and cast it as a Border. Here is a quick example of this:
Xaml
<Grid>
<ItemsControl x:Name="items">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border>
<TextBlock MouseEnter="TextBlock_MouseEnter" MouseLeave="TextBlock_MouseLeave" Text="{Binding}" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
Code behind
public Page()
{
InitializeComponent();
items.ItemsSource = new string[] { "This", "Is", "A", "Test" };
}
private void TextBlock_MouseEnter(object sender, MouseEventArgs e)
{
var tx = sender as TextBlock;
var bd = tx.Parent as Border;
bd.Background = new SolidColorBrush(Colors.Yellow);
}
private void TextBlock_MouseLeave(object sender, MouseEventArgs e)
{
var tx = sender as TextBlock;
var bd = tx.Parent as Border;
bd.Background = new SolidColorBrush(Colors.White);
}
The example sets the background on the border by grabbing the parent of the textbox.
Bryant
2008-11-12 19:20:25
A:
see this: http://msdn.microsoft.com/en-us/library/bb613579.aspx and this: http://blogs.msdn.com/wpfsdk/archive/2007/04/16/how-do-i-programmatically-interact-with-template-generated-elements-part-ii.aspx. Unfortunately, it won't work in SL because SL DataTemplate class doesn't have the FindName method.
morpheus
2010-05-13 19:17:38