清除文本框时,属性的值不会更改

本文关键字:属性 文本 清除 | 更新日期: 2024-09-21 02:17:08

我有一个名为HaemogramViewModel 的ViewModel

这是代码:

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;
    }
}

在我的主窗口ViewModel 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属性的血红蛋白字段。

当我在文本框中输入一些值,然后单击保存按钮时,一切都很好。

现在的问题是:

当我在文本框中输入一些值时,我按tab键,然后再次单击文本框,然后清除文本框中的值。现在,如果我点击保存按钮,那么我不会得到文本框的值=null,相反,我会得到文本框值=我之前输入的值。

清除文本框时,属性的值不会更改

试试这个,它可以

<TextBox Text="{Binding B, UpdateSourceTrigger=PropertyChanged, TargetNullValue=''}"/>

并且在您的视图中,模型属性应该声明为以下

 private double? b;
    public double? B
    {
        get
        {
            return b;
        }
        set
        {
            b = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("B"));
            }
        }
    }

在xmal中,您必须将属性UpdateSourceTrigger=PropertyChanged设置为

    <TextBox Text="{Binding Path=Property, UpdateSourceTrigger=PropertyChanged}"/>

默认UpdateSourceTrigger=LostFocus,这意味着一旦按下tab键或失去焦点,绑定到textBox的属性就会更新。如果设置为PropertyChanged,它将为textBox 中的每个字符更改更新属性