简体   繁体   English

C#数据绑定标签不会刷新

[英]C# Databound Label wont refresh

I am databinding an object value to a label and it wont refresh. 我将一个对象值绑定到标签,它不会刷新。

lblTime.DataBindings.Add(new Binding("Text", AppSettings.Instance.SelectedAuction, "EndDate", false, DataSourceUpdateMode.OnPropertyChanged));

The bind works and using a messagebox, I know the value is changing. 绑定工作,并使用消息框,我知道值正在更改。 I am correctly using the INotifyChanged but it wont work. 我正确使用了INotifyChanged,但无法正常工作。 Changing individual values works, say: 更改单个值是可行的,例如:

AppSettings.Instance.SelectedAuction.EndDate = ((Auction)lbAuctions.SelectedItem).EndDate;

But I want to replace the whole object, and it wont update: 但是我想替换整个对象,并且它不会更新:

AppSettings.Instance.SelectedAuction = (Auction)lbAuctions.SelectedItem;

Why is this? 为什么是这样? I can make individual values refresh but not the object itself... 我可以刷新单个值,但不能刷新对象本身。

public Auction SelectedAuction
    {
        get { return this.selectedAuction; }
        set
        {
            this.CheckPropertyChanged<Auction>
            ("SelectedAuction", ref this.selectedAuction, ref value);
        }
    }

Is it that there is another method to use when replacing the object itself or something additional i need to ref? 是在替换对象本身时使用另一种方法还是我需要参考的其他方法?

The data binding that is setup on lblTime is set on the object reference by AppSettings.Instance.SelectedAuction at the time of the call to AddBinding . lblTime上设置的数据绑定是在调用AddBinding时通过AppSettings.Instance.SelectedAuction在对象引用上设置的。 The databinding subscribes to the PropertyChanged event on that object. 数据绑定订阅该对象上的PropertyChanged事件。 Changing the SelectedAuction on your Instance doesn't change that. 更改Instance上的SelectedAuction不会改变它。 The data binding is still subscribed on the original object. 数据绑定仍在原始对象上订阅。 (This also means you have a memory lead, since the data binding references the original CurrentAuction , that instance will not be garbage collected) (这也意味着您有一条内存条,因为数据绑定引用了原始的CurrentAuction ,所以该实例将不会被垃圾回收)

You need to instead setup the data binding so that it can listed for events on the Instance object. 您需要改为设置数据绑定,以便可以为Instance对象上的事件列出数据绑定。 You would have to set the binding to "CurrentAuction.EndDate" . 您必须将绑定设置为"CurrentAuction.EndDate" This will not work directly (* see note below), but there is a helper object, BindingSource , that can be put in the middle that will support that binding. 这将不能直接工作(*请参阅下面的注释),但是可以在中间放置一个辅助对象BindingSource ,它将支持该绑定。 Below is an example: 下面是一个示例:

BindingSource bs = new BindingSource();
bs.DataSource = AppSettings.Instance;
lblTime.DataBindings.Add("Text", bs, "CurrentAuction.EndDate", false, 
      DataSourceUpdateMode.OnPropertyChanged);

Note: It will work without a BindingSource in 3.5, but not in 4.0, see Does data binding support nested properties in Windows Forms? 注意:在3.5中没有BindingSource情况下将可以使用,但在4.0中则不能使用,请参阅数据绑定是否支持Windows窗体中的嵌套属性?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM