3 回答

TA貢獻(xiàn)1995條經(jīng)驗(yàn) 獲得超2個(gè)贊
我將模型的 int 屬性包裝在一個(gè)字符串屬性中,因?yàn)?TextBox.Text 是一個(gè)字符串,其他任何東西都會(huì)產(chǎn)生轉(zhuǎn)換錯(cuò)誤。
ViewModel 需要自己的字符串,而不是總是將用戶的輸入轉(zhuǎn)換為 int,因?yàn)橛脩艨赡軙?huì)清除該框,或者在鍵入“-1”的過(guò)程中部分輸入了一個(gè)不是有效數(shù)字的值。當(dāng)您收到轉(zhuǎn)換錯(cuò)誤時(shí),WPF 綁定無(wú)法更新視圖模型,因此您不知道有問(wèn)題。
private string firstArgument;
public string FirstArgument
{
get
{
return this.firstArgument;
}
set
{
this.firstArgument= value;
int tempInt;
if (int.TryParse(value, out tempInt))
{
this.Model.FirstArgument = tempInt;
}
this.NotifyPropertyChanged();
}
}
以下是我用來(lái)驗(yàn)證字符串是否為有效 int 的大部分代碼。
protected void NotifyPropertyChanged([CallerMemberName]string propertyName = null)
{
this.CheckForPropertyErrors();
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public override void CheckForPropertyErrors()
{
this.ValidateInt(this.FirstArgument , nameof(this.FirstArgument ));
}
protected void ValidateInt32(string value, string fieldName, string displayName = null)
{
int temp;
if (!int.TryParse(value, out temp))
{
this.AddError(new ValidationError(fieldName, Constraints.NotInt32, $"{displayName ?? fieldName} must be an integer"));
}
else
{
this.RemoveError(fieldName, Constraints.NotInt32);
}
}

TA貢獻(xiàn)1874條經(jīng)驗(yàn) 獲得超12個(gè)贊
int變量的默認(rèn)值為0。我想,這會(huì)幫助你
private int? _number1;
public int? firstargument
{
get { return _number1; }
set
{
this._number1 = value;
this.OnPropertyChanged("firstargument");
}
}

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超5個(gè)贊
原因
您在運(yùn)行窗口中獲得 a 的原因0是您的綁定屬性都是int并且0是 a 的默認(rèn)值int。
0of anint是 XAML 綁定系統(tǒng)的有效值,因此在您鍵入任何內(nèi)容之前,您會(huì)看到所有TextBoxes 都包含 a 。0
解決方案
您的所有屬性都應(yīng)該是 astring并轉(zhuǎn)換您的實(shí)際數(shù)字:
private int? _number1;
public string FirstArgument
{
get => _number1?.ToString();
set
{
if (int.TryParse(value, out var number))
{
_number1 = number;
OnPropertyChanged("FirstArgument");
}
else
{
_number1 = null;
}
}
}
注意:
因?yàn)槟赡軙?huì)得到一個(gè)無(wú)法轉(zhuǎn)換為的文本
int
,所以您可以int?
在輸入錯(cuò)誤號(hào)時(shí)使用它來(lái)存儲(chǔ)空值。將您的數(shù)字轉(zhuǎn)換為字符串或從字符串轉(zhuǎn)換,以便它可以正確顯示到您的 XAML 綁定系統(tǒng)中。
該屬性應(yīng)該是字符串,不能是 an,
int?
因?yàn)?XAML 綁定系統(tǒng)不會(huì)自動(dòng)將 a 轉(zhuǎn)換string
為 anint
,除非您自己轉(zhuǎn)換或編寫新的IValueConverter
.
更新
要實(shí)現(xiàn)該Add命令,只需使用字段而不是屬性。
private void AddNumbers()
{
var a = _number1?.Value ?? 0;
var b = _number2?.Value ?? 0;
var c = a + b;
_addedargument = c;
}
如果要將結(jié)果存儲(chǔ)到模型中,則存儲(chǔ)a, b,c值。
- 3 回答
- 0 關(guān)注
- 295 瀏覽
添加回答
舉報(bào)