0

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;
    }
}
pinkfloydx33
  • 11,863
  • 3
  • 46
  • 63
SimonH
  • 5
  • 2
  • Refer this article https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-override-the-tostring-method – Vivek Nuna Jun 07 '20 at 15:25
  • You can create private variables that store DateTime in string and public getter to retrieve that string in that ToString override – Jawad Jun 07 '20 at 15:26
  • Does this answer your question? [WPF: How do I apply custom formatting to a ListView?](https://stackoverflow.com/questions/2144292/wpf-how-do-i-apply-custom-formatting-to-a-listview) quick googling suggests this applies to gridview as well – pinkfloydx33 Jun 07 '20 at 16:38

2 Answers2

1

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"; 
        }
    }
}
Jino Shaji
  • 1,097
  • 14
  • 27
0

It is not a good idea to modify your model data class to alter what you see in a view. Most platforms that display model data objects have a way of modifying what you are seeing, based on the raw data.

Depending on the stack you are using, search for modifying the view based on raw data instead. If you can show your UI code, we can be of further help.

Kemal Bagci
  • 71
  • 1
  • 4