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您需要的字符串操作。

看起來你想在你的數據網格上有動態列,我建議你在後面的代碼中生成數據模板,這樣你就可以在那裏解析你的綁定路徑和源名稱,然後把它作爲單元格模板或單元格編輯模板。