【问题标题】:NumericUpDown DataBinding property not updating when value changesNumericUpDown DataBinding 属性在值更改时不更新
【发布时间】:2018-08-01 17:39:53
【问题描述】:

我正在尝试对 NumericUpDown WinForm 控件执行 DataBinding。执行绑定按设计工作,但是我遇到了一个问题,即在元素失去焦点之前,值不会被推送到绑定属性。当控件中的值发生变化而不需要失去焦点时,我是否缺少一些东西来更新属性?

如果按设计工作,有没有办法在不失去焦点的情况下强制更新属性?

逻辑:

using System;
using System.Windows.Forms;

public partial class Form1 : Form
{
    private NumericUpDown numericUpDown1 = new NumericUpDown();
    private ExampleData _ed = new ExampleData();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // Define the UI Control
        numericUpDown1.DecimalPlaces = 7;
        numericUpDown1.Location = new System.Drawing.Point(31, 33);
        numericUpDown1.Name = "numericUpDown1";
        numericUpDown1.Size = new System.Drawing.Size(120, 20);
        numericUpDown1.TabIndex = 0;

        // Add the UI Control
        Controls.Add(numericUpDown1);

        // Bind the property to the UI Control
        numericUpDown1.DataBindings.Add("Value", _ed, nameof(_ed.SampleDecimal));

        numericUpDown1.ValueChanged += NumericUpDown1_ValueChanged;
    }

    private void NumericUpDown1_ValueChanged(object sender, EventArgs e)
    {
        // This will fire as you change the control without losing focus.
        System.Diagnostics.Debugger.Break();
    }
}

public class ExampleData
{
    public decimal SampleDecimal
    {
        get { return _sampleDecimal; }
        set
        {
            // This set isn't called until after you lose focus of the control.
            System.Diagnostics.Debugger.Break();
            _sampleDecimal = value;
        }
    }

    private decimal _sampleDecimal = 1.0m;
}

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    将您的绑定更改为:

    numericUpDown1.DataBindings.Add(nameof(NumericUpDown.Value), _ed, nameof(ExampleData.SampleDecimal), false, DataSourceUpdateMode.OnPropertyChanged);
    

    这将确保绑定在值更改时触发,而不是在您将焦点从控件移开时触发。

    如果您希望能够从代码更新 SampleDecimal 并在您的 numericupdown 上更新,您需要在 SampleData 类上实现 INotifyPropertyChanged 接口,如下所示:

    public class ExampleData : INotifyPropertyChanged
    {
    
        protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        public decimal SampleDecimal
        {
            get { return _sampleDecimal; }
            set
            {
                _sampleDecimal = value;
                OnPropertyChanged();
            }
        }
    
        private decimal _sampleDecimal = 1.0m;
    }
    

    【讨论】:

    • 这么简单的东西,唉...谢谢你的帮助!
    猜你喜欢
    • 1970-01-01
    • 2013-12-09
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2020-02-11
    • 2019-11-25
    • 2019-03-24
    相关资源
    最近更新 更多