0

我知道我在做什么很奇怪,但我希望它能够工作。我感觉有些不对劲。

我的资源中定义了一个 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++;            
        }
}
4

1 回答 1

0

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

看来您希望在数据网格上有动态列,我建议您在代码中生成数据模板,以便您可以在那里解析绑定路径和源名称,然后将其附加为单元格模板或单元格编辑模板。

于 2010-10-12T13:57:57.957 回答