[英]How can I modify a binding so that it adds “ pts” if the bound value is not “”?
I am using a ViewModel to set the number of points on my display. 我正在使用ViewModel设置显示器上的点数。 Is there a way that I could modify this so that when the value of points is "0" or another not empty that it adds " pts" but when it's "" it still displays ""
有没有一种方法可以对此进行修改,以便当点的值为“ 0”或另一个不为空时,它添加“ pts”,但当其为“”时仍显示“”
string _points;
public string Points
{
get => _points;
set => SetProperty(ref _points, value);
}
Do a check if the _string
is "0"
before returning it to the view, in your Points
property: 在
_string
返回到视图之前,在Points
属性中检查_string
是否为"0"
:
get => _points.Equals("0") ? "0 pts" : _points;
And to tidy it up, put it into a method: 并整理一下,将其放入方法中:
public string ReturnPoints() => _points.Equals("0") ? "0 pts" : _points;
And then in your Points
property: 然后在您的
Points
属性中:
string _points;
public string Points
{
get => ReturnPoints();
set => SetProperty(ref _points, value);
}
From your question, you can try this. 根据您的问题,您可以尝试一下。
use string.IsNullOrEmpty
method to check string whether empty, if no append pts to the end string, otherwise return ""
. 使用
string.IsNullOrEmpty
方法检查字符串是否为空,如果没有将pts附加到末尾字符串,否则返回""
。
string _points;
public string Points
{
get => !string.IsNullOrEmpty(_points) ? $"{_points} pts" : string.Empty;
set => SetProperty(ref _points, value);
}
Based on replys from OP on my other answer. 根据OP对我其他答案的答复。
public static Points _points { get; set; }
class Points
{
private int? i;
public static implicit operator Points(int value)
{
return new Points { i.Value = value };
}
public static implicit operator string(Points value)
{
if(Value.i.HasValue)
return value.i.Value.ToString();
return "";
}
public static implicit operator int(Points value)
{
return value.I.HasValue ?value.i.value : 0;
}
}
and using the new Points struct: 并使用新的Points结构:
_points += 2; // 2
string s = points; // "2"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.