清除文本框时属性的值不会改变 [英] Value of the property does not change when the textbox is cleared
问题描述
我有一个名为 HaemogramViewModel 的 ViewModel
I have a ViewModel Called HaemogramViewModel
代码如下:
public class HaemogramViewModel : INotifyPropertyChanged
{
public HaemogramViewModel()
{
}
public Haemogram CurrentHaemogramReport
{
get
{
return MainWindowViewModel.cHaemogram;
}
set
{
MainWindowViewModel.cHaemogram = value;
OnPropertyChanged("CurrentHaemogramReport");
}
}
protected virtual void OnPropertyChanged(string PropertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(PropertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
在我的 MainWindowViewModel 类中:
In my MainWindowViewModel Calss:
class MainWindowViewModel : INotifyPropertyChanged
{
public MainWindowViewModel()
{
cHaemogram = new Haemogram();
}
public static Haemogram cHaemogram { get; set; }
private void SaveChanges(object obj)
{
using (Lab_Lite_Entities db = new Lab_Lite_Entities())
{
//db.Patients.Add(CurrentPatient);
if (cHaemogram != null)
{
if (cHaemogram.Haemoglobin != null)
{
db.Haemograms.Add(cHaemogram);
}
}
}
}
}
我的文本框绑定到 CurrentHaemogram 属性的 Hemoglobin 字段.
My textbox is bound to the field Haemoglobin of CurrentHaemogram Property.
当我在文本框中输入一些值然后单击保存按钮时,一切正常.
When I enter some value in the textbox and then click save button then everything works fine.
现在的问题是:
当我在文本框中输入某个值时,我按 Tab 键,然后再次单击文本框,然后清除文本框中的值.现在,如果我点击保存按钮,那么我不会得到文本框的值 = null,而是得到文本框的值 = 我之前输入的值.
When I enter some value in the textbox then I press tab and then again click on textbox and then clear the value in the textbox. Now if I click on save button then I don't get the textbox's value = null, instead I get the textbox's value = the value that I entered previously.
推荐答案
试试看吧
<TextBox Text="{Binding B, UpdateSourceTrigger=PropertyChanged, TargetNullValue=''}"/>
并且在您的视图中模型属性应如下声明
and in you view model property should be declared as below
private double? b;
public double? B
{
get
{
return b;
}
set
{
b = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("B"));
}
}
}
这篇关于清除文本框时属性的值不会改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!