WPF - 如何将转换器应用于所有DataGridTextColumn?

时间:2017-10-18 20:04:05

标签: c# wpf converter

我想使用WPF Apply Converter将Binding Value绑定到应用程序中的所有DataGridTextColumn。

对于单个DataGridTextColumn转换器正常工作:


app(ResponseFactory::class)->setResponse([[
    'url.path' => "/curltest/$curlTargetEndpont",
    'response' => 'success'
]]);

但是在应用程序中,我在不同的DataGrid中获得了很多(超过100个)DataGridTextColumn,我知道最佳解决方案,而不是单独申请每个列转换器。

我知道使用Style有可能为所有类型的控件修改某些属性(例如前景)但不确定如何将它们用于绑定值和转换器?

1 个答案:

答案 0 :(得分:1)

您可以借助全局样式和附加属性来完成此操作。您无法为DataGridTextColumn创建全局样式(或任何样式),因为它不会从FrameworkElement继承。但是,您可以为DataGrid本身创建样式,为该样式中的网格设置附加属性,并在添加它们时为所有列绑定添加该附加属性集转换器的属性更改处理程序。示例代码:

public class DataGridHelper : DependencyObject {
    public static IValueConverter GetConverter(DependencyObject obj) {
        return (IValueConverter) obj.GetValue(ConverterProperty);
    }

    public static void SetConverter(DependencyObject obj, IValueConverter value) {
        obj.SetValue(ConverterProperty, value);
    }

    public static readonly DependencyProperty ConverterProperty =
        DependencyProperty.RegisterAttached("Converter", typeof(IValueConverter), typeof(DataGridHelper), new PropertyMetadata(null, OnConverterChanged));

    private static void OnConverterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
        // here we have our converter
        var converter = (IValueConverter) e.NewValue;
        // first modify binding of all existing columns if any
        foreach (var column in ((DataGrid) d).Columns.OfType<DataGridTextColumn>()) {
            if (column.Binding != null && column.Binding is Binding)
            {
                ((Binding)column.Binding).Converter = converter;
            }
        }
        // then subscribe to columns changed event and modify binding of all added columns
        ((DataGrid) d).Columns.CollectionChanged += (sender, args) => {
            if (args.NewItems != null) {
                foreach (var column in args.NewItems.OfType<DataGridTextColumn>()) {
                    if (column.Binding != null && column.Binding is Binding) {
                        ((Binding) column.Binding).Converter = converter;
                    }
                }
            }
        };
    }
}

然后在某处创建全局样式(如App.xaml):

<Application.Resources>
    <local:TestConverter x:Key="decimalConverter" />
    <Style TargetType="DataGrid">
        <Setter Property="local:DataGridHelper.Converter"
                Value="{StaticResource decimalConverter}" />
    </Style>
</Application.Resources>