你可以在全球風格和附屬性的幫助下做到這一點。您不能爲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