你可以在全球风格和附属性的帮助下做到这一点。您不能为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>
来源
2017-10-18 20:58:51
Evk
在我的情况下,当类似的问题出现了,我结束了修改每一个喜欢你的样品中,然后chassing放下任何剩余物。无聊和容易出错,但不能想象WPF更好。 – Alejandro
所以你想添加一个转换器,所有的DataGridTextColumn.Bindings,甚至非十进制? – Evk
设计DataGridTextColumn并不那么容易。 [DataGridTextColumn](https://msdn.microsoft.com/en-US/library/system.windows.controls.datagridtextcolumn(v = vs.110).aspx)不从FrameworkElement继承。 – Link