You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF中以编程方式编写DataGridTextColumn Binding运行报错求助

解决DataGridTextColumn绑定字符串格式的运行时错误

问题场景

已有XAML实现:

<DataGridTextColumn Header="blabla" Binding="{Binding uet,StringFormat=0.00;-0.00;#}"/>

尝试用C#编程实现类似逻辑,编写了如下代码,但执行eng.Binding = new Binding(f.Name+strf);时出现运行时错误:

string? strf="";
var eng = new DataGridTextColumn();
if (f.PropertyType == typeof(string))
{ strf = "";}
else if(f.PropertyType == typeof(int))
{
    strf = ",StringFormat=0;-0;#";
}
else if (f.PropertyType == typeof(int))
{
    strf = ",StringFormat=0.00;-0.00;#";
}
eng.Header = atrddd.DisplayName;
eng.CanUserSort = true;
eng.Width = DataGridLength.Auto;
eng.Binding = new Binding(f.Name+strf);
this.list1.Columns.Add(eng);

错误原因

  1. 语法混淆:你把XAML绑定特有的逗号分隔附加属性语法,直接拼接到了C#的Binding构造函数路径参数里,这是错误的——C#代码中需要通过Binding对象的专属属性来设置StringFormat,不能复用XAML的语法写法。
  2. 逻辑错误:代码里重复判断了f.PropertyType == typeof(int),第二个分支永远不会被执行,应该改为判断浮点类型(比如double、decimal)。

正确实现代码

var eng = new DataGridTextColumn();
// 单独创建Binding对象,避免语法混淆
var binding = new Binding(f.Name);

if (f.PropertyType == typeof(string))
{
    // 字符串类型无需格式化
}
else if (f.PropertyType == typeof(int))
{
    binding.StringFormat = "0;-0;#";
}
else if (f.PropertyType == typeof(double) || f.PropertyType == typeof(decimal))
{
    binding.StringFormat = "0.00;-0.00;#";
}

eng.Header = atrddd.DisplayName;
eng.CanUserSort = true;
eng.Width = DataGridLength.Auto;
eng.Binding = binding;
this.list1.Columns.Add(eng);

补充说明

  • C#中创建Binding时,所有绑定参数(比如StringFormat、Converter等)都需要通过Binding对象的对应属性单独设置,不能像XAML那样直接拼在路径里。
  • 可根据实际数据类型扩展判断分支,比如需要支持float类型,可在浮点判断分支里加入|| f.PropertyType == typeof(float)。

内容的提问来源于stack exchange,提问作者Bob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 20:12:28