c# - 在标题中使用 '/' 时如何防止列不显示在 WPF 数据网格中?

标签 c# wpf wpfdatagrid

<分区>

我的应用程序中有一个 WPF 数据网格,我在其中将 ItemSource 的值设置为我构建的 DataTable 的 DefaultView。问题在于,每当我将 DataTable 中其中一列的 ColumnName 设置为包含“/”的字符串时,标题就会显示在 DataGrid 控件中,但值不会。我该如何解决这个问题?

enter image description here

这是用“-”替换“/”的同一张表 enter image description here

顺便说一句,这似乎也发生在带有“.”的标题中。在他们中。所以任何小数都会导致相同的行为。

我的网格定义为

<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));
    }
}

关于c# - 在标题中使用 '/' 时如何防止列不显示在 WPF 数据网格中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25017542/

相关文章:

c# - 如何以编程方式设置 WPF DataGrid 的模板和填充内容?

c# - datagrid鼠标双击事件wpf

c# - 我想为使用 Linq To Sql 读取的数据集中的每条记录添加一个唯一 ID

javascript - 如何从特定选定行的事件发送者数据中获取模型数据?

c# - 通过控制边距移动图像

c# - TextChanged/LostFocus/等。 DataGridTextColumn 事件

c# - 如何在没有按钮的情况下折叠数据网格?

c# - 使用 VS2015 Update 1 编译时表达式破坏代码

c# - for 循环总是只执行一次

wpf - 如何将 wpf 窗口移动到负顶部值?