我正在以编程方式创建一个 DataGrid,它工作正常,但 RowHeaders 没有正确显示。文本显然在那里,因为工具提示显示了正确的内容,但它在标题中显示为空白。显然我无法发布屏幕截图 - 它显示了一个大约 10 行的网格,标题为 150 宽,但其中没有任何内容,然后是几列数据。
下面是创建 DataGrid 的代码:
seisTraceHeaderGrid = new DataGrid
{
AutoGenerateColumns = false,
HorizontalAlignment = HorizontalAlignment.Stretch,
VerticalAlignment = VerticalAlignment.Stretch,
HorizontalScrollBarVisibility = ScrollBarVisibility.Visible,
VerticalScrollBarVisibility = ScrollBarVisibility.Visible,
HorizontalContentAlignment = HorizontalAlignment.Stretch,
HeadersVisibility = DataGridHeadersVisibility.All,
IsReadOnly = true,
CanUserAddRows = false,
CanUserDeleteRows = false,
CanUserReorderColumns = false,
CanUserResizeColumns = true,
CanUserResizeRows = true,
CanUserSortColumns = false,
SelectionMode = DataGridSelectionMode.Single,
SelectionUnit = DataGridSelectionUnit.Cell,
RowHeight = 25,
ColumnWidth = 75,
};
seisTraceHeaderGrid.AlternatingRowBackground = (Brush)Resources["AlternateRowBackgroundBrush"];
seisTraceHeaderGrid.ColumnHeaderStyle = (Style)Resources["ColumnHeaderStyle"];
seisTraceHeaderGrid.LoadingRow += dg_LoadingRow;
// set up the row headers
DataTemplate rowHeaderTemplate = new DataTemplate();
rowHeaderTemplate.DataType = typeof(RowHeaderNode);
FrameworkElementFactory textHolder = new FrameworkElementFactory(typeof(Label));
textHolder.SetBinding(ContentProperty,
new Binding("RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGridRow}}, Path=Header"));
rowHeaderTemplate.VisualTree = textHolder;
seisTraceHeaderGrid.RowHeaderTemplate = rowHeaderTemplate;
// add a column for each trace
for (int traceId = 0; traceId < ViewModel.Nodes[0].Count; traceId++) {
seisTraceHeaderGrid.Columns.Add(
new DataGridTextColumn
{
Header = string.Format(" {0}", traceId + 1),
Binding = new Binding(string.Format("[{0}]", traceId))
}
);
}
// add some dummy columns to make it prettier
for (int traceId = ViewModel.Nodes[0].Count; traceId < 5; traceId++) {
seisTraceHeaderGrid.Columns.Add(
new DataGridTextColumn
{
Header = string.Format(" {0}", ""),
Binding = new Binding(string.Format("[{0}]", ""))
}
);
}
seisTraceHeaderGrid.RowHeaderWidth = 150;
seisTraceHeaderGrid.ItemsSource = ViewModel.Nodes;
baseGrid.Children.Add(seisTraceHeaderGrid);
以及将文本放入 RowHeader 标签的方法:
private void dg_LoadingRow(object sender, DataGridRowEventArgs e)
{
e.Row.Header = string.Format("[{0:000}]", ViewModel.RowHeaders[e.Row.GetIndex()].Offset) + " : " + ViewModel.RowHeaders[e.Row.GetIndex()].Name;
}
我没有做什么?蒂亚!
珍妮