NoOne
NoOne

Reputation: 4091

WPF DataGrid - Can I decorate my POCOs with attributes to have custom column names?

I have a DataGrid in WPF and fill it with data like this:

public enum Sharing
{
    Equal,
    SurfaceBased,
}

public class Data
{
    public bool Active { get; set; }
    public string Name { get; set; }
    public int Floor { get; set; }
    public Sharing Sharing { get; set; }
}
    public ObservableCollection<Data> _col = new ObservableCollection<Data>()
                                 {
                                  new Data(){Active = true, Name = "KRL", Floor = 0 },
                                  new Data(){Name = "DAT", Floor = 1},
                                  new Data(){Name = "TRE", Floor = 1},
                                  new Data(){Name = "DUO", Floor = 2},
                                 };

    public MainWindow()
    {
        InitializeComponent();

        grid.AutoGenerateColumns = true;
        grid.DataContext = _col;
        grid.ItemsSource = _col;
    }

I was wondering if I could use some attributes on the enumerations and the POCO class so that the DataGrid displays them (instead of the variable names) on the headers and ComboCoxes.

Something like this:

public enum Sharing
{
    [Name("This is a test")]
    Equal,
    [Name("This is a test 2")]
    SurfaceBased,
}

Is this possible?

Upvotes: 3

Views: 1356

Answers (1)

NoOne
NoOne

Reputation: 4091

OK. Here is the way to do it for the Headers:

You add attributes, like Description attributes to your Properties.

public class MyPOCO
{
    [Description("The amount you must pay")]
    public float Amount { get; set; }
}

Then, in a class derived from DataGrid you do this:

    protected override void OnAutoGeneratingColumn(DataGridAutoGeneratingColumnEventArgs e)
    {
        try
        {
            base.OnAutoGeneratingColumn(e);
            var propDescr = e.PropertyDescriptor as System.ComponentModel.PropertyDescriptor;
            e.Column.Header = propDescr.Description;
        }
        catch (Exception ex)
        {
            Utils.ReportException(ex);
        }
    }

For adding custom names to the members of the enumerations, you need to make a custom column. You can see a simple example here : https://stackoverflow.com/a/17510660/964053.

Upvotes: 3

Related Questions