如何在ViewModel中更改字符串属性的值?

我想在视图中显示一些文本,但是如果文本长度超过600个字符,我希望截断并在末尾添加省略号。如果文字少于600个字符,我将显示未修改的整个字符串。

我在想一些类似的事情:

public string Description 
{
    get 
    {
        int txtLen = Description?.Length ?? 0;
        int maxLen = 600;
        if (txtLen > 0)
        {
            string ellipsis = txtLen > maxLen ? "…" : "";
            return Description.Substring(0,txtLen > maxLen ? maxLen : txtLen) + ellipsis;
        }
        else
        { 
            return "";
        }
    }
    set 
    {
        Description = value;
    }
}

上面的代码可以编译,但是当我尝试运行它时,我的应用程序超时并显示“拒绝连接”错误消息。如果将属性更改为public string Description { get; set; },则我的应用程序将运行。

我需要设置器,因为我在应用程序的其他地方,都修改了控制器中的Description属性。

更新

感谢史蒂夫的解决方案。但是,当截断起作用时,我意识到有时我实际上希望在视图中显示整个文本。因此,我提出了另一种方法,该方法使用原始的Description而不是private string _dsc

public string Description { get; set; }

public string DescriptionTruncate(int maxLen)
{
    int txtLen = Description?.Length ?? 0;
    if (txtLen > 0)
    {
        string ellipsis = txtLen > maxLen ? "…" : "";
        return Description.Substring(0,txtLen > maxLen ? maxLen : txtLen) + ellipsis;
    }
    else
    {
        return "";
    }
}
ab13521 回答:如何在ViewModel中更改字符串属性的值?

您在get访问器中的代码将引发一个Stack Overflow异常,因为要测量Description的长度,您可以调用get访问器,并且直到堆栈溢出停止您的代码时,它才会结束。

要解决您的问题,请使用后端变量并对其进行处理

private string _dsc = "";
public string Description
{
    get
    {
        int txtLen = _dsc.Length;
        int maxLen = 600;
        if (txtLen > 0)
        {
            string ellipsis = txtLen > maxLen ? "..." : "";
            return _dsc.Substring(0,txtLen > maxLen ? maxLen : txtLen) + ellipsis;
        }
        else
        {
            return "";
        }
    }
    set
    {
        _dsc = value;
    }
}
,

您是否不想在CSS中执行此操作?

https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow

对我来说,这比在视图模型中做得更干净。

本文链接:https://www.f2er.com/3127248.html

大家都在问