0

我知道我很奇怪我在做什么,但我希望这个工作。我感觉有点不对劲。WPF DataTemplateColumn访问DataTemplate并设置ItemsSource

我有我的资源定义一个DataTemplate如下:

<UserControl.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="../ParameterEditorResourceDictionary.xaml"></ResourceDictionary> 
      <ResourceDictionary> 

       <DataTemplate x:Key="ParameterDefault"> 
        <StackPanel Orientation="Horizontal"> 
         <TextBlock Text="("></TextBlock> 
         <ItemsControl ItemsSource="{//I need to set from code}"> 
          //some code here 
         </ItemsControl> 
         <TextBlock Text=")"></TextBlock> 
        </StackPanel> 
       </DataTemplate> 

      </ResourceDictionary> 
     </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary>  
</UserControl.Resources> 

我在我的XAML具有加载事件定义一个DataGrid。

<cc:PEDataGrid AutoGenerateColumns="False" 
       Loaded="CommonPEGrid_Loaded">   
</cc:PEDataGrid> 

在我的事件处理程序代码中,我想设置在我的DataTemplate中定义的ItemsControl的ItemsSource。我后面的代码看起来是这样的:

private void CommonPEGrid_Loaded(object sender, RoutedEventArgs e) 
    { 
     int i = 0; 
     DataGrid dg = sender as DataGrid; 

     DataGridTemplateColumn column = null; 

     //ParametersAllLoops is a ObservableCollection 

     foreach (ParameterLoop obj in ParametersAllLoops) 
     { 
      column = new DataGridTemplateColumn(); 
      column.Header = "Loop (" + i.ToString() + ")"; 

      DataTemplate dt = null; 

      //Here I want to write code 
      //I want to access the DataTemplate defined in resources 
      //and set the ItemsSource of ItemsControl to something like this 
      // xxx.ItemsSource = obj; and then assign the DataTemplate to 
      //the CellTemplate of column. 
      //**Note :: ParameterLoop object has the IList Parameters** 


      column.CellTemplate = dt; 

      dg.Columns.Add(column); 
      i++;    
     } 
} 

回答

0

您可以通过使用方法FindResource()资源,并将其转换为DataTemplate中,但为其分配的ItemSource您需要的字符串操作。

看起来你想在你的数据网格上有动态列,我建议你在后面的代码中生成数据模板,这样你就可以在那里解析你的绑定路径和源名称,然后把它作为单元格模板或单元格编辑模板。