我有一个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>
答案 0 :(得分: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;
}