在Silverlight ItemsControl中查找与某个项目对应的UI元素 [英] Find UI element corresponding to an item in a Silverlight ItemsControl

查看:59
本文介绍了在Silverlight ItemsControl中查找与某个项目对应的UI元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Silverlight ItemsControl显示的字符串列表. DataTemplate是一个以TextBlock作为其子元素的Border控件.如何访问与项目相对应的边框控件?例如,我可能想这样做以更改背景颜色.

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.

推荐答案

更简单的方法是获取文本块的父级并将其转换为边框.这是一个简单的例子:

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>

后面的代码

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.

这篇关于在Silverlight ItemsControl中查找与某个项目对应的UI元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆