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>

У меня есть DataGrid, определенный в моем xaml, который имеет загруженное событие.

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

В моем коде обработчика событий я хочу установить ItemsSource of ItemsControl, определенный в моем DataTemplate. Мой код выглядит следующим образом:

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++;            
        }
}

1 ответ

Вы можете найти ресурс с помощью метода FindResource() и привести его к DataTemplate, но чтобы назначить его ItemSource, вам потребуется манипулирование строками.

Кажется, что вы хотите иметь динамические столбцы в вашей таблице данных, я бы посоветовал вам создать шаблон данных в коде, чтобы вы могли разрешить пути привязки и имена источников, а затем присоединить его как шаблон ячейки или шаблон редактирования ячейки.

Другие вопросы по тегам