Nobody Important
Nobody Important

Reputation:

Find UI element corresponding to an item in a Silverlight ItemsControl

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.

Upvotes: 1

Views: 3444

Answers (3)

morpheus
morpheus

Reputation: 20330

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.

Upvotes: 0

Bryant
Bryant

Reputation: 8670

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.

Upvotes: 2

jarda
jarda

Reputation: 51

You can override the ItemsControl.GetContainerForItemOverride method and save the object-container pairs in a dictionary.

Upvotes: 0

Related Questions