Dot NET
Dot NET

Reputation: 4897

Why is Display being ignored?

I've got a DataGrid, which is bound to the following window and model class:

public partial class AttributesWindow
    {
        public ObservableCollection<AttributesModel> ItemsSource { get; set; }

        private readonly List<string> _fields = new List<string>(new[] { "Test1", "Test2" });
        public ObservableCollection<AttributesModel> itemsSource { get; set; }
        private DatabaseTable parentDatabaseTable = null;

        public AttributesWindow(DatabaseTable parentDatabaseTable)
        {
            this.parentDatabaseTable = parentDatabaseTable;
            InitializeComponent();
            DataContext = this;
            itemsSource = new ObservableCollection<AttributesModel>(_fields.Select(f => new AttributesModel(f)));
        }
    }

public class AttributesModel
    {
        public string Field { get; private set; }

        [Display(Name = "Sort Order")]
        public SortOrder SortBy { get; set; }

        [Display(Name = "Group By")]
        public string GroupBy { get; set; }

        [Display(Name = "Having")]
        public string Having { get; set; }

        [Display(Name = "Display Order")]
        public string DisplayOrder { get; set; }

        [Display(Name = "Aggregate By")]
        public Aggregate AggregateBy { get; set; }

        public enum Aggregate
        {
            None,
            Sum,
            Minimum,
            Maximum,
            Average
        }

        public enum SortOrder
        {
            Unsorted,
            Ascending,
            Descending
        }

        public AttributesModel(string field)
        {
            Field = field;
        }
    }

For some reason or other, the [Display(Name = "Sort Order")] properties are all being ignored, and the headers of my DataGrid are taking on the property names.

<DataGrid Name="dgAttributes" 
                  ItemsSource="{Binding itemsSource}" 
                  AutoGenerateColumns="True" 
                  CanUserAddRows="False" 
                  CanUserDeleteRows="False" 
                  CanUserReorderColumns="False" 
                  CanUserResizeColumns="False" 
                  CanUserResizeRows="False"
                  CanUserSortColumns="False"
                  ColumnWidth="Auto"
                  >
</DataGrid>

Upvotes: 0

Views: 114

Answers (1)

Andrii Shvydkyi
Andrii Shvydkyi

Reputation: 2286

If your bind you DataGrid to DataTable it also will ignore Caption property of columns. As for me, this is a bug in grid columns auto-generation but you can workaround it by handling AutoGeneratingColumn event.

void DataGrid_AutoGeneratingColumn_1(object sender, DataGridAutoGeneratingColumnEventArgs e) {
  PropertyDescriptor pd = (PropertyDescriptor)e.PropertyDescriptor;
  var da = (DisplayAttribute)pd.Attributes[typeof(DisplayAttribute)];
  if (da != null)
  e.Column.Header = da.Name;
} 

Upvotes: 1

Related Questions