Find UI element corresponding to an item in a Silverlight ItemsControl

孤街醉人 提交于 2019-12-01 13:02:26

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.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!