在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.