如何在视图模型中处理数字框ValueChanged事件?

问题描述

我试图检测用户何时更改了数字框值,并在我的视图模型中对其进行处理。

数字DoubleBox在XAML中的定义如下:

<numeric:DoubleBox Value="{Binding LeadR}" Grid.Column="1" MinValue="0" MaxValue="1000" IsEnabled="{Binding IsNotMeasuring}" ValueChanged="{Binding DoubleBox_ValueChanged}"/>

在我的viewmodel.cs中:

private void DoubleBox_ValueChanged(object sender,ValueChangedEventArgs<double?> e)
{
    // Omitted Code: Insert code that does something whenever the text changes...
}

当我在XAML中右键单击DoubleBox_ValueChanged并单击“转到定义”时,它将导航到WM中的方法。但是当我运行代码时,Visual Studio显示错误

System.Windows.Markup.XamlParseException: ''Provide value on 'System.Windows.Data.Binding' threw an exception.' Line number '123' and line position '162'.'

enter image description here

有人可以告诉我如何解决吗?

解决方法

您使用的是后台代码,而不是viewmodel;该错误意味着您没有将DataContext与Window / UserControl /包含DoubleBox的任何对象相关联。您必须设置一个ViewModel并将其绑定到DoubleBox的容器以使绑定工作。我给你一个简单的例子。

public class ViewModel : INotifyPropertyChanged
    {

        private double _leadR;
        public double LeadR
        {
            get
            {
                return _leadR;
            }
            set
            {
                _leadR = value;
                OnPropertyChanged(nameof(LeadR));
                OnLeadRChanged();
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(propertyName));
        }

        private void OnLeadRChanged()
        {
            //Do whatever you want with the new value of LeadR
        }
    }

然后在您的容器中,甚至可以在构造器中设置DataContext

public class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                this.DataContext = new ViewModel();
            }
        }

希望这对您的问题有所帮助。

,

如果您想对DoubleBox上的值更改做出反应,只需在LeadR的设置器中进行即可。

private double _leadr;
public double LeadR
{
   get => _leadr;
   set
   {
      if (Math.Abs(_leadr - value) > 10E-12)
      {
         _leadr = value;
         OnPropertyChanged();

         // The value changed,do something with it here
      }
   }
}

您不需要,也不应处理视图模型中的ValueChanged事件。其他选项包括编写附加属性,触发动作或行为,但这可能对您要实现的目标来说很复杂。

由于XamlParseException的内部异常是InvalidCastException,因此您获得的绑定异常似乎源自使用错误的类型。