簡體   English   中英

數值更改時,NumericUpDown DataBinding屬性不會更新

[英]NumericUpDown DataBinding property not updating when value changes

我正在嘗試對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;
}

更改對此的綁定:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM