Search code examples
c#overridingtostring

How to customize GridViewColumn display for properties of class?


I have a class Article with several properties. I want to know whether it is possible to override the ToString method for the bool and DateTime properties so that for the booleans they print as "Yes/No" and the DateTime as custom text.

Idea is that when these properties are printed in a ListView with GridViewColumn bound to every property they don't print standard ToString values.

public class Article
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    public string Title { get; set; }
    public string Author { get; set; }
    public string Content { get; set; }
    public int NumberOfWords { get; set; }
    public string Category { get; set; }
    public bool CanBePublished { get; set; }
    public bool Published { get; set; }
    public int Length { get; set; }
    public DateTime CreationDate { get; set; }

    public Article() { }

    public Article(string title, string author, string content, int numberOfWords, string category, bool canBePublished, int length)
    {
        Title = title;
        Author = author;
        Content = content;
        NumberOfWords = numberOfWords;
        Category = category;
        CanBePublished = canBePublished;
        Length = length;
        Published = false;
        CreationDate = DateTime.Now;
    }
}

Solution

  • You can define get method to get the formatted value from those fields as shown below. Create a view model class for that and do it in this way by difining a get method. and use that property to read the data. Like Article_ViewModelObject.CreationDateVal

    public class Article_ViewModel: Article
    {
         public string CreationDateVal  
        {
            get
            {
                return  CreationDate.ToString(); 
            }
        }
         public string CanBePublishedVal  
        {
            get
            {
                return CanBePublished ? "Yes" : "No"; 
            }
        }
    }