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

DataTemplates特定のデータを画面に表示する方法を説明する設計図のようなものです。DataTemplate は単なるリソースです。複数の要素で共有できます。DataTemplateは から派生したものではないため、単独で/をFrameworkElement持つことはできません。ある要素にa を適用すると、暗黙的に適切なデータ コンテキストが与えられます。DataContextDatabindingDataTemplate

したがって、テンプレートを何かに適用しない限り、境界のあるデータを取得することはできないと思います。

于 2013-10-30T09:28:13.250 に答える
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 に答える