public static void SetDataAdapter <TSource, TData>(this System.Windows.Controls.DataGrid dataGrid, IWpfDataAdapter <TSource, TData> adapter) where TData : class, new() { var dataType = typeof(TData); dataType.GetProperties().ToList().ForEach(property => { var metadata = property.GetCustomAttribute <WpfColumnAttribute>(true); if (metadata == null) { return; } var column = new DataGridTextColumn() { Header = metadata.DisplayName, Binding = new System.Windows.Data.Binding(property.Name), IsReadOnly = true }; switch (metadata.WidthRule) { case ColumnWidthRule.Value: column.Width = metadata.Width; break; case ColumnWidthRule.AutoSize: column.Width = DataGridLength.Auto; break; case ColumnWidthRule.SizeToCells: column.Width = DataGridLength.SizeToCells; break; case ColumnWidthRule.SizeToHeader: column.Width = DataGridLength.SizeToHeader; break; default: throw new InvalidOperationException($"Unsupported width rule '{metadata.WidthRule}'"); } if (!string.IsNullOrEmpty(metadata.CellStyle)) { column.CellStyle = dataGrid.FindResource(metadata.CellStyle) as Style; } if (!string.IsNullOrEmpty(metadata.HeaderStyle)) { column.HeaderStyle = dataGrid.FindResource(metadata.HeaderStyle) as Style; } dataGrid.Columns.Add(column); }); dataGrid.ItemsSource = adapter; }
private static Style CreateElementStyle(DataGrid dataGrid, string bindingPath) { var baseStyle = dataGrid.FindResource("TextBlockBaseStyle") as Style; var style = new Style(typeof(TextBlock), baseStyle); AddSetters(style, bindingPath); return style; }
/// <summary> /// Create a new filter host for the given data grid. /// </summary> /// <param name="dataGrid">The data grid to filter.</param> internal DataGridFilterHost(DataGrid dataGrid) { Contract.Requires(dataGrid != null); _dataGrid = dataGrid; dataGrid.Columns.CollectionChanged += Columns_CollectionChanged; dataGrid.Loaded += DataGrid_Loaded; if (dataGrid.ColumnHeaderStyle != null) return; // Assign a default style that changes HorizontalContentAlignment to "Stretch", so our filter symbol will appear on the right edge of the column. var baseStyle = (Style)dataGrid.FindResource(typeof(DataGridColumnHeader)); var newStyle = new Style(typeof(DataGridColumnHeader), baseStyle); newStyle.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty, HorizontalAlignment.Stretch)); dataGrid.ColumnHeaderStyle = newStyle; }