0

我用过下面的代码

    <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>
4

3 回答 3

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)
于 2013-10-30T09:43:35.020 回答
0

DataTemplates就像蓝图一样,描述了特定数据应如何在屏幕上显示。数据模板只是资源。它们可以由多个元素共享。DataTemplate不是从 派生的FrameworkElement,因此它们不能拥有DataContext/Databinding自己。当您将 aDataTemplate应用于某个元素时,它会隐含地被赋予适当的数据上下文。

所以,我想,除非您将模板应用于某些东西,否则您将无法获得有界数据。

于 2013-10-30T09:28:13.250 回答
0

为了访问在 a 中定义的元素DataTemplate,我们首先需要获取 a ContentPresenter。我们可以ContentPresenter从一个DataTemplate应用了它的项目中获取。然后我们可以访问DataTemplatefrom theContentPresenter然后使用该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);
于 2013-10-30T09:23:00.643 回答