首页 > 解决方案 > 如何为类的属性自定义 GridViewColumn 显示?

问题描述

我有一个具有多个属性的类文章。我想知道是否可以覆盖boolDateTime属性的 ToString 方法,以便将布尔值打印为“是/否”,将日期时间打印为自定义文本。

想法是,当这些属性ListViewGridViewColumn绑定到每个属性的方式打印时,它们不会打印标准ToString值。

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

标签: c#overridingtostring

解决方案


您可以定义 get 方法以从这些字段中获取格式化的值,如下所示。为此创建一个视图模型类,并通过定义 get 方法以这种方式完成。并使用该属性读取数据。像Article_ViewModelObject.CreationDateVal

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

推荐阅读