我的应用程序中有一个 WPF 数据网格,我在其中将 ItemSource 的值设置为我构建的 DataTable 的 DefaultView。问题在于,每当我将 DataTable 中其中一列的 ColumnName 设置为包含“/”的字符串时,标题就会显示在 DataGrid 控件中,但值不会。我该如何解决这个问题?
这是用“-”替换“/”的同一张表
顺便说一句,这似乎也发生在带有“.”的标题中。在他们中。所以任何小数都会导致相同的行为。
我的网格定义为
<DataGrid x:Name="dgLFKPI" />
并且我在代码后面设置值(是的,它应该在 View 模型和 MVVM 中,但它是一个遗留的应用程序,正在慢慢地朝着这个方向发展)。
dgLFKPI.ItemsSource = dt.DefaultView;
绑定(bind)路径解析器错误地解析了列名中的特殊字符。
所以绑定(bind)到 3/4
的列实际上只绑定(bind)到属性 3
,而不是属性 3/4
。 (与 .
绑定(bind)相同)
当它运行时,您可能会在调试窗口中看到绑定(bind)错误,应该说同样的事情。
System.Windows.Data Error: 40 : BindingExpression path error:
'3' property not found on 'object' ''DataRowView'
根据 this answer
There are a number of different characters which have special meaning
in a binding path including full stop ('.'), slash ('/'), square
brackets ('[',']') and parenthesis ('(',')'), the parenthesis will
cause your app to crash. These special characters can be escaped by
surrounding the binding path with square brackets. More information
about paths and character escaping can be found in the [Binding
Declarations Overview][2]
该链接问题还包含一个 good solution用于处理想要使用自动生成的列的网格。
使用 AutoGeneratingColumn
事件,并手动为名称中包含这些特殊字符的列创建绑定(bind),以使用方括号对它们进行转义。
<DataGrid x:Name="dgLFKPI"
AutoGeneratingColumn="dgLFKPI_AutoGeneratingColumn" />
private void dgLFKPI_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName.Contains('/') && e.Column is DataGridBoundColumn)
{
var col = e.Column as DataGridBoundColumn;
col.Binding = new Binding(string.Format("[{0}]", e.PropertyName));
}
}