0

我有一个 DataGrid,它绑定到以下窗口和模型类:

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;
        }
    }

出于某种原因,[Display(Name = "Sort Order")]所有属性都被忽略了,并且我的 DataGrid 的标题正在使用属性名称。

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

1 回答 1

1

如果您将 DataGrid 绑定到 DataTable,它也会忽略列的 Caption 属性。至于我,这是网格列自动生成中的一个错误,但您可以通过处理 AutoGeneratingColumn 事件来解决它。

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;
} 
于 2012-10-27T07:05:25.437 回答