WPF中如何使用代码操作数据模板生成的控件
2008-04-29 17:25
931 查看
有一个Listbox,里面的Item是通过数据模板生成的,如下所示:
Listbox使用的数据模板如下:
使用下面的代码就可以获取数据模板里面TextBlock中的内容了。
上面代码调用的函数如下:
原文出处:http://blogs.msdn.com/wpfsdk/archive/2007/04/16/how-do-i-programmatically-interact-with-template-generated-elements-part-ii.aspx
参考:http://msdn.microsoft.com/zh-cn/library/bb613579.aspx
<Border Margin="15" BorderBrush="Aqua" BorderThickness="2" Padding="8" CornerRadius="5"> <StackPanel> <ListBox Name="myListBox" ItemTemplate="{StaticResource myDataTemplate}" IsSynchronizedWithCurrentItem="True"> <ListBox.ItemsSource> <Binding Source="{StaticResource InventoryData}" XPath="Books/Book"/> </ListBox.ItemsSource> </ListBox> <Button Margin="10" Click="DataTemplateFindElement">Get text of textBlock in DataTemplate</Button> </StackPanel> </Border>
Listbox使用的数据模板如下:
<DataTemplate x:Key="myDataTemplate"> <TextBlock Name="textBlock" FontSize="14"> <TextBlock.Text> <Binding XPath="Title"/> </TextBlock.Text> </TextBlock> </DataTemplate>
使用下面的代码就可以获取数据模板里面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 named TextBlock in the DataTemplate of the selected list item: " + myTextBlock.Text);
上面代码调用的函数如下:
private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject { { { childItem childOfChild = FindVisualChild<childItem>(child); if (childOfChild != null) return childOfChild; } } return null; }
原文出处:http://blogs.msdn.com/wpfsdk/archive/2007/04/16/how-do-i-programmatically-interact-with-template-generated-elements-part-ii.aspx
参考:http://msdn.microsoft.com/zh-cn/library/bb613579.aspx
相关文章推荐
- WPF中如何使用代码操作数据模板生成的控件
- WPF中如何使用代码操作数据模板生成的控件
- 分类网站中这种模式如下 如果不使用Datalist 将如何编制 使用怎样的控件操作 希望哪位大虾 提供相关代码
- C#分析数据库结构,使用XSL模板自动生成代码 - 清清月儿 .NET万花筒 Asp.net技术 Asp.net教程 Asp.net源码 Asp.net基础 Asp.net控件 Asp.net入门 - CSDNBlog
- 如何高效地使用XCodeFactory自动生成的数据层代码(一)
- C# 程序中如何向(DEV)ComboBoxEdit控件中添加下拉列表的值不使用数据绑定,就是使用代码添加
- silverlight3 datagrid c#中动态生成模板列(日期格式)使用IValueConvert对绑定数据的格式化操作
- 如何高效地使用XCodeFactory自动生成的数据层代码(二)
- 使用xml 和merge 维护表数据的代码生成脚本
- 发一个自己写的小工具,生成类似petshop4的数据操作方面的代码
- 创建代码生成器可以很简单:如何通过T4模板生成代码?[上篇]
- http://hi.baidu.com/xckouy/item/c6b6024fcafc2bac61d7b9d5 java根据模板自动生成文档数据换行操作
- ListView动态加载数据模板(使用代码布局)
- 使用 T4 文本模板生成设计时代码
- 如何通过 Visual C# 使 Excel 自动执行操作以使用数组来填充或获取某区域中的数据
- 【转】- 使用T4模板批量生成代码
- 章鱼哥—VB.NET 如何实现代码自动生成控件 添加绑定事件
- WinForm中如何使用WPF中的控件
- [转]黄聪:如何使用CodeSmith批量生成代码
- 创建代码生成器可以很简单:如何通过T4模板生成代码?[下篇]