2017-10-18 180 views
3

我想使用WPF应用转换器绑定到应用程序中的所有DataGridTextColumn值。WPF - 如何将转换器应用于所有DataGridTextColumn?

对于单DataGridTextColumn转换器做工精细:

<DataGridTextColumn 
    Header ="Value" 
    Binding="{Binding Value, Converter={StaticResource decimalConverter}}" 
    /> 

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

我知道使用样式有可能修改某些属性的所有类型的控件(例如前景),但不知道如何使用这些绑定值和转换器?

+0

在我的情况下,当类似的问题出现了,我结束了修改每一个喜欢你的样品中,然后chassing放下任何剩余物。无聊和容易出错,但不能想象WPF更好。 – Alejandro

+0

所以你想添加一个转换器,所有的DataGridTextColumn.Bindings,甚至非十进制? – Evk

+0

设计DataGridTextColumn并不那么容易。 [DataGridTextColumn](https://msdn.microsoft.com/en-US/library/system.windows.controls.datagridtextcolumn(v = vs.110).aspx)不从FrameworkElement继承。 – Link

回答

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> 
+0

它对我来说工作得很好!感谢您快速解决。 – Kaspar

相关问题