我有一个DataTable
,其中一个列名称中有结尾空格。
让我们说,我们在数据库中有表:
CREATE TABLE [dbo].[Text_with_pk](
[char_ 10 ] [char](10) NOT NULL,
[nchar_10] [nchar](10) NOT NULL,
[varchar_max] [varchar](max) NOT NULL,
[id] [int] IDENTITY(1,1) NOT NULL,
CONSTRAINT [PK_Text_with_pk] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
列[char_ 10 ]
在其名称中包含结尾空格。
我将此表的内容读入DataTable
并将其绑定到DataGrid
。
<DataGrid Grid.Row="2"
x:Name="PreviewDataGrid"
AutoGenerateColumns="True"
SelectedValuePath="SelectedCells"
SelectedCellsChanged="PreviewDataGrid_OnSelectedCellsChanged"
ItemsSource="{Binding Data}"
AutoGeneratingColumn="PreviewDataGrid_OnAutoGeneratingColumn">
</DataGrid>
我尝试添加列绑定以转义列名中的特殊符号/空格。
private void PreviewDataGrid_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
var column = (e.Column as DataGridTextColumn);
if (column != null)
{
column.Binding = new Binding($"[{e.PropertyName}]");
column.Header = e.PropertyName;
column.Binding.TargetNullValue = "NULL";
}
}
但它不起作用,我不断收到此错误:
System.Windows.Data Error: 17 : Cannot get 'Item[]' value (type 'Object') from '' (type 'DataRowView'). BindingExpression:Path=[QOF754 ]; DataItem='DataRowView' (HashCode=19681030); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String') TargetInvocationException:'System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: QOF754 is neither a DataColumn nor a DataRelation for table [dbo].[Test].
at System.Data.DataRowView.get_Item(String property)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at MS.Internal.Data.PropertyPathWorker.GetValue(Object item, Int32 level)
at MS.Internal.Data.PropertyPathWorker.RawValue(Int32 k)'
我事先不知道表格结构,列名。所以我需要处理所有场景。
此处[QOF754 ]
是实际的列名。
我试图在Converter
中撤消它:
ItemsSource="{Binding Data, Converter={StaticResource DataGridConverter}}"
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return null;
var dataTable = value as DataTable;
if (dataTable != null)
{
foreach (DataColumn column in dataTable.Columns)
{
column.ColumnName = column.ColumnName.Trim();
}
}
return value;
}
但是列名不同(修剪),这对我不起作用。
如何将这些带尾随空格的列绑定到我的DataGrid并使其正常工作?