我使用了以下代码
<DataTemplate x:Key="myTemplate">
<TextBlock Text="Hi"></TextBlock>
</DataTemplate>
在这种情况下,我可以使用下面的代码
来获取文本块文本DataTemplate myTemplate = this.Resources["myTemplate"] as DataTemplate;
TextBlock rootElement = myTemplate.LoadContent() as TextBlock;
//I can get the text "rootElement.text "
但是当我使用绑定意味着我无法获得文本
<DataTemplate x:Key="myTemplate">
<TextBlock Text="{Binding EmployeeName}"></TextBlock>
</DataTemplate>
答案 0 :(得分:0)
为了访问DataTemplate
内定义的元素,我们首先需要获得ContentPresenter
。我们可以从已应用ContentPresenter
的项目中获取DataTemplate
。然后,我们可以从DataTemplate
访问ContentPresenter
,然后使用FindName
方法访问其元素。以下是MSDN上How to: Find DataTemplate-Generated Elements页面的示例,您应该阅读以获取完整详细信息:
// Getting the currently selected ListBoxItem
// Note that the ListBox must have
// IsSynchronizedWithCurrentItem set to True for this to work
ListBoxItem myListBoxItem = (ListBoxItem)
(myListBox.ItemContainerGenerator.ContainerFromItem(myListBox.Items.CurrentItem));
// Getting the ContentPresenter of myListBoxItem
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);
// Finding textBlock from the DataTemplate that is set on that ContentPresenter
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
TextBlock myTextBlock = (TextBlock)
myDataTemplate.FindName("textBlock", myContentPresenter);
// Do something to the DataTemplate-generated TextBlock
MessageBox.Show("The text of the TextBlock of the selected list item: " +
myTextBlock.Text);
答案 1 :(得分:0)
DataTemplates
就像蓝图一样,描述了如何在屏幕上显示特定数据。 DataTemplates只是资源。它们可以被多个元素共存。 DataTemplate不是来自FrameworkElement
,因此他们不能自己拥有DataContext
/ Databinding
。将DataTemplate
应用于某个元素时,会隐式给出适当的数据上下文。
所以,我想,除非你将模板应用到某些东西,否则你将无法获得有界数据。
答案 2 :(得分:0)
使用DataBinding
时,您可以获得文字,甚至更轻松。您应该记住的只是模板的DataContext
。如果您在ListBox
中使用模板 - 则上下文将特别Item
,即:
public class Employee : INotifyPropertyChanged
{
public string EmployeeName
{
get
{
return this.employeeName;
}
set
{
this.employeeName = value;
this.OnPropertyChanged("EmployeeName");
}
}
...
}
在ViewModel
:
public class EmployeeViewModel : INotifyPropertyChanged
{
public List<Employee> Employees
{
get
{
return this.employees;
}
set
{
this.employees = value;
this.OnPropertyChanged("Employees");
}
}
...
}
xaml
:
<ListBox ItemsSource={Binding Employees}>
<ListBox.ItemTemplate>
<DataTemplate x:Key="myTemplate">
<TextBlock Text="{Binding EmployeeName}"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
有了这样的结构,你就有了
ListBox | Value source
Employee0 | (Employees[0].EmployeeName)
Employee1 | (Employees[1].EmployeeName)
... | ...
EmployeeN | (Employees[n].EmployeeName)