簡體   English   中英

具有數據綁定為null屬性值的NumericUpDown控件不起作用

[英]NumericUpDown control with DataBinding to null property value not working

我有一種方法可以將數字向上設置以顯示對象中屬性的值。 該屬性值可以為null 如果是這種情況,我希望數字向下顯示零。 這是我正在使用的代碼:

    private void NudNullBindingSetup(NumericUpDown nud, MyObject obj, string propertyName)
    {
        var b = new Binding("Value", obj, propertyName, true,
                            DataSourceUpdateMode.OnPropertyChanged)
        {
            NullValue = 0,
            DataSourceNullValue = null
        };
        nud.DataBindings.Add(b);
    }

如果我在NumericUpDown中放置一個值,然后使用對該屬性具有null的對象調用此綁定,則控件仍將顯示原始值。

順便說一句,如果對象實際上在屬性中具有值,則此方法將完美工作。

我錯過了什么?

編輯:我應該注意這是一個null而不是object屬性中的DBNull.Value

編輯

您可以簡單地設置:

NullValue = (decimal)0,
DataSourceNullValue = null

它按預期工作。

原版的

您可以使用Format事件解決問題。

將數據從數據源推入控件時,將引發Format事件。 您可以處理Format事件,以將數據源中的未格式化數據轉換為可顯示的格式化數據。

例如,這是我寫的內容,並且按預期工作:

private void NudNullBindingSetup(NumericUpDown nud, MyObject obj, string propertyName)
{
    var b = new Binding("Value", obj, propertyName, true, DataSourceUpdateMode.OnPropertyChanged);
    b.NullValue = 0;                /*Only used in Format event*/
    b.DataSourceNullValue = null;   /*Only used in Format event*/
    b.Format += (s, e) =>
    {
        var binding = (Binding)s;
        var control = (NumericUpDown)binding.Control;

        control.Value =
            e.Value == binding.DataSourceNullValue ?
                (int)binding.NullValue : ((int?)e.Value).Value;
    };
    nud.DataBindings.Add(b);
}

這是MyObject

public class MyObject
{
    public int? Value { get; set; }
}

暫無
暫無

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

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