如何在WPF和Silverlight中取得DataTemplate中的命名元素
1个回答
推荐于2016-12-06
展开全部
1.假如ListBox使用如下的DataTemplate
<DataTemplate x:Key="myDataTemplate">
<TextBlock Name="textBlock" FontSize="14" Foreground="Blue">
<TextBlock.Text>
<Binding XPath="Title"/>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
2.在cs文件中写如下的代码可以找到某个ListBoxItem对应的TextBlock
ListBoxItem myListBoxItem =
(ListBoxItem)(myListBox.ItemContainerGenerator.ContainerFromItem(myListBox.Items.CurrentItem));
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
TextBlock myTextBlock = (TextBlock)myDataTemplate.FindName("textBlock", myContentPresenter);
MessageBox.Show("The text of the TextBlock of the selected list item: "
+ myTextBlock.Text);
private childItem FindVisualChild<childItem>(DependencyObject obj)
where childItem : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is childItem)
return (childItem)child;
else
{
childItem childOfChild = FindVisualChild<childItem>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
SilverLight
1. Xmal 和WPF中相同
2. 由于SL中的DataTemplate没有FindName方法,因此c#代码有所区别
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询