c# - 清除文本框时属性的值不会更改

标签 c# wpf mvvm

我有一个名为 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;

    }
}

在我的 MainWindowViewModel 调用中:

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

我的文本框绑定(bind)到 CurrentHaemogram 属性的字段 Hemoglobin。

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

现在的问题是:

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

最佳答案

试一试吧

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

并且在您的 View 模型属性中应声明如下

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

关于c# - 清除文本框时属性的值不会更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20579731/

相关文章:

C# vb : System. Func占用多少内存?

c# - MVVM灯下的异步命令执行

c# - 在哪里使用 MVVM 中的 Web 服务?

c# - 当设计中已经存在一个或多个选项卡时,如何在 WPF MVVM 中动态添加选项卡控件

c# - 我需要做什么才能在 C# 中实现 "out of proc"COM 服务器?

C# 主项目和子项目引用

c# - 为 .cs 文件编辑解析器

c# - ControlTemplate 与 DataTrigger 对比带有 DataTemplateSelector 的 DataTemplate

javascript - 如何在 Neutronium 库中执行 javascript?

c# - 如何检查线程是否完成,然后在 C#/WPF 中填充进度条