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

How can I change the value of a string property within the ViewModel?

我想在我的视图中显示一些文本,但如果文本超过 600 个字符,我想 t运行cate 并在末尾添加一个省略号。如果文本少于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;
    }
}

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

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

更新

感谢史蒂夫提供解决方案。然而,当 t运行cation 起作用时,我意识到有时我实际上想要在视图中显示整个文本。所以我做了一个额外的方法,它使用原来的 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 "";
    }
}

您在 get 访问器中的代码将引发堆栈溢出异常,因为要测量您调用 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

我觉得这比在你的视图模型中做更干净。