【发布时间】:2020-09-12 14:49:34
【问题描述】:
我想将一些数据绑定到在我后面的代码中动态创建的列。它适用于DataGridTextColumn,但不适用于DataGridTemplateColumn。
由于 DataGridTemplateColumn 没有“绑定”属性,我创建了一个从 DataGridTemplateColumn 派生的自定义列,正如一些解决方案所建议的那样。但是,SetBinding 在调用 GenerateElement 方法时会抛出 System.Exception 并使程序崩溃。
class DataGridBoundColumn : DataGridTemplateColumn
{
public BindingBase Binding { get; set; }
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
{
var element = base.GenerateEditingElement(cell, dataItem);
if (element != null && Binding != null)
element.SetBinding(ContentPresenter.ContentProperty, Binding);
return element;
}
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
var element = base.GenerateElement(cell, dataItem);
if (element != null && Binding != null)
element.SetBinding(ContentPresenter.ContentProperty, Binding);//Error is here
return element;
}
}
用于创建列和填充网格的代码:
dataGrid.Columns.Add(new Models.DataGridBoundColumn
{
Header = " Week" + week.WeekNumber,
Binding = new Binding { Path = new PropertyPath("[" + i.ToString() + "]") },
CellTemplate = (DataTemplate)Resources["templateCell"]
});
var collection = new ObservableCollection<object>();
List<string> list = new List<string>(new string[] { "2", "3", "7" });
for (int i= 0; i < list.Count; i++)//Trying with some test data
{
collection.Add(list);
}
dataGrid.ItemsSource = collection;
我目前用于测试的DataTemplate:
<DataTemplate x:Key="templateCell">
<StackPanel>
<TextBlock Text="{Binding WeekNumber}" />
<Rectangle HorizontalAlignment="Left" Height="18" Width="20" Fill="{Binding ItemColor}" />
</StackPanel>
</DataTemplate>
我仔细查看了绑定类文档,但我仍然不知道为什么它会抛出这个异常......
错误是:
灾难性故障(HRESULT 异常:0x8000FFFF (E_UNEXPECTED))
在 Windows.UI.Xaml.FrameworkElement.SetBinding(DependencyProperty dp, BindingBase 绑定)在 Application.Models.DataGridBoundColumn.GenerateElement(DataGridCell 单元格,对象数据项)在 C:...\Models\DataGridBoundColumn.cs:line 26 在 Microsoft.Toolkit.Uwp.UI.Controls.DataGrid.PopulateCellContent(布尔 isCellEdited, DataGridColumn dataGridColumn, DataGridRow dataGridRow, 数据网格单元数据网格单元)在 Microsoft.Toolkit.Uwp.UI.Controls.DataGrid.AddNewCellPrivate(DataGridRow 行,DataGridColumn 列)在 Microsoft.Toolkit.Uwp.UI.Controls.DataGrid.CompleteCellsCollection(DataGridRow 数据网格行)在 Microsoft.Toolkit.Uwp.UI.Controls.DataGrid.GenerateRow(Int32 rowIndex, Int32 插槽,对象数据上下文)在 Microsoft.Toolkit.Uwp.UI.Controls.DataGrid.AddSlots(Int32 totalSlots) 在 Microsoft.Toolkit.Uwp.UI.Controls.DataGrid.RefreshRows(布尔 recycleRows,布尔值 clearRows)在 Microsoft.Toolkit.Uwp.UI.Controls.DataGrid.RefreshRowsAndColumns(布尔 清除行)在 Microsoft.Toolkit.Uwp.UI.Controls.DataGrid.MeasureOverride(大小 可用大小)
【问题讨论】:
-
能否附上完整的异常信息?
-
刚刚添加了完整的堆栈跟踪
-
谢谢。我将“Défaillance irrémédiable”替换为“Catastrophic failure”,因为我认为这是正确的英文翻译,否则请重新编辑!
-
这能回答你的问题吗? Catastrophic failure in xaml binding
-
之前看到过,我觉得不是同一个问题