我想使用WPF应用转换器绑定到应用程序中的所有DataGridTextColumn值。
对于工作良好的单个DataGridTextColumn转换器:
<DataGridTextColumn
Header ="Value"
Binding="{Binding Value, Converter={StaticResource decimalConverter}}"
/>但是在应用程序中,我在不同的DataGrid中获得了许多(超过100个) DataGridTextColumn,并且我知道最好的解决方案,而不是分别应用每个列转换器。
我知道使用样式可以为所有类型的控件(例如前台)修改一些属性,但不确定如何将这些属性用于绑定值和转换器?
发布于 2017-10-18 20:58:51
您可以借助全局样式和附加属性来完成此操作。您不能为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>https://stackoverflow.com/questions/46818329
复制相似问题