Динамически построить вложенный WPF DataGrid - PullRequest
0 голосов
/ 09 сентября 2011

Я нашел много кода на этом сайте и других, которые показывают, как создать вложенную сетку данных в XAML, но я не могу найти какую-либо информацию о том, как использовать код C # для получения тех же результатов.То, что я хотел бы сделать, это преобразовать это:

<DataGrid ...>
  <DataGrid.Columns>
    <DataGridTextColumn Header="Received Date" Binding="{Binding Received}" .../>
     ...
  </DataGrid.Columns>
  <DataGrid.RowDetailsTemplate>
     <DataTemplate>
        <DataGrid ItemsSource="{Binding Details}" ...>
           <DataGrid.Columns>
              <DataGridTextColumn Header="Log Date" Binding="{Binding LogDate}" />
              ...
           </DataGrid.Columns>
         </DataGrid>
      </DataTemplate>
    </DataGrid.RowDetailsTemplate>
  <DataGrid>

в C # код.

Структура данных выглядит примерно так:

public class MessageData {
   Guid MessageId {get; set;}
   DateTime ReceivedDate { get; set; }
   ...
   List<EventDetail> Details { get; set; }
}

public class EventDetail {
   Guid MessageId { get; set; }
   DateTime LogDate { get; set; }
   string LogEvent { get; set; }
   ...
}

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

DataGrid dg = new DataGrid();
...
dg.IsReadOnly = true;
FrameworkElementFactory details = FrameworkElementFactory(typeof(DataGrid));
details.SetBinding(ItemsControl.ItemsSourceProperty, new Binding("Details"));
details.SetValue(DataGrid.AutoGenerateColumnsProperty, true);
DataTemplate dt = new DataTemplate(typeof(DataGrid));
dt.VisualTree = details;
dt.RowDetailsTemplate = dt;
dg.ItemsSource = myDataSouce;

это работает, но когда я устанавливаю AutoGenerateColumns в false - и пытаюсь определить столбцы, это терпит неудачу...

1 Ответ

1 голос
/ 09 сентября 2011

Создание DataGrid в программном коде - это просто выполнение следующих действий:

var dataGrid = new DataGrid();

Столбцы DataGrid можно добавить в программном коде, см. Следующий пример из MSDN :

//Create a new column to add to the DataGrid
DataGridTextColumn textcol = new DataGridTextColumn();
//Create a Binding object to define the path to the DataGrid.ItemsSource property
//The column inherits its DataContext from the DataGrid, so you don't set the source
Binding b = new Binding("LastName");
//Set the properties on the new column
textcol.Binding = b;
textcol.Header = "Last Name";
//Add the column to the DataGrid
DG2.Columns.Add(textcol);

Вероятно, самая сложная часть кода - создать шаблон строки.Построение DataTemplates в коде было рассмотрено в других вопросах:

Создание DataTemplate в коде за

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...