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

如何在WPF DataGrid中动态修改字符串货币显示格式

问题原因

ConverterCulture 是绑定标记扩展的普通CLR属性,不是依赖属性,本身不支持动态绑定,所以你直接给它套Binding语法就会报错。


可行实现方案(推荐用自定义多值转换器)

这个方案改造成本最低,适配性最好:

  1. 先实现多值转换器,用来接收价格和动态的货币文化信息,自行处理格式化逻辑:
using System.Globalization;
using System.Windows.Data;

public class DynamicCurrencyConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        // 校验入参:第一个参数是价格数值,第二个是你要切换的货币文化
        if (values.Length != 2 
            || !decimal.TryParse(values[0]?.ToString(), out decimal price) 
            || values[1] is not CultureInfo currencyCulture)
        {
            return string.Empty;
        }
        // 按传入的动态文化输出货币格式
        return price.ToString("C", currencyCulture);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        // 如果你的价格列是只读的,不需要实现回转逻辑,需要编辑的话自行补充货币字符串转数值的逻辑即可
        throw new NotImplementedException();
    }
}
  1. 在XAML中引入转换器作为资源:
<!-- 对应你的窗口/页面的Resources节点,local命名空间替换成你转换器所在的命名空间 -->
<Window.Resources>
    <local:DynamicCurrencyConverter x:Key="DynamicCurrencyConverter" />
</Window.Resources>
  1. 改造DataGrid列的绑定,用多值绑定同时绑定价格和你的CurrencyCulture变量:
<DataGridTextColumn Header="Price" Width="95">
    <DataGridTextColumn.Binding>
        <MultiBinding Converter="{StaticResource DynamicCurrencyConverter}">
            <Binding Path="Price" />
            <!-- 这里的绑定路径替换成你CurrencyCulture属性的实际路径,比如放在全局ViewModel就写对数据源即可 -->
            <Binding Path="DataContext.CurrencyCulture" RelativeSource="{RelativeSource AncestorType=Window}" />
        </MultiBinding>
    </DataGridTextColumn.Binding>
</DataGridTextColumn>

注意事项

  • 存放CurrencyCulture属性的类需要实现INotifyPropertyChanged接口,属性变更时发出通知,界面才会同步刷新格式。
  • 如果需要同时支持多列货币,这个转换器可以复用,不需要重复实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 11:36:03