单击bindingnavigator add new时,在窗体上启用字段

时间:2014-06-02 16:40:36

标签: winforms data-binding bindingsource

我在C#Winforms应用程序中使用了BindingNavigator。

如果bindingSource中没有记录,我希望禁用表单中的字段。 为此,我将字段放在面板上,并希望使用类似

的内容绑定面板的enabled属性
this.panel1.DataBindings.Add(new Binding("Enabled", this, "HasRecord", false, DataSourceUpdateMode.OnPropertyChanged));

this.bindingSource1.AddingNew += this.BindingSourceListAddingNew<Person>;

在表单加载事件中。

我在表单上实现了INotifyPropertyChanged并设置了一个HasRecord属性,当单击添加新按钮时会调用该属性

但是,我似乎无法找到一个属性,当单击“添加”按钮时,该属性将返回true。 以下是表单中的方法。

我的问题是,如何让HasRecord属性工作? 我可以添加一个模块宽的布尔变量并将其设置在BindingSourceAddingNew中,但这看起来像是一个黑客。

    public bool HasRecord { get
    {
         return this.bindingSource1.Count > 0;

    } }

      public override void BindingSourceListAddingNew<T>(object sender, AddingNewEventArgs e)
    {
        base.BindingSourceListAddingNew<T>(sender, e);
        this.SendChange("HasRecord");
        Debug.Print( this.bindingSource1.SupportsChangeNotification.ToString());

    }

1 个答案:

答案 0 :(得分:1)

部分问题似乎与bindingSource1.Count有关,直到调用AddingNew方法之后才会更新。即,您添加的第一个记录仍会导致HasRecord返回0,因此在添加第二个记录之前,面板不会启用。相反,在绑定源上使用ListChanged事件似乎可以解决这个问题。

使用以下代码会导致面板在加载时被禁用,然后在将记录添加到bindingSource1到button1_Click时立即启用。你仍然需要手动提升PropertyChanged,我不确定你是否试图避免这种情况。

public partial class Form1 : Form , INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

    public Form1()
    {
        InitializeComponent();
    }

    public bool HasRecord
    {
        get
        {
            return this.bindingSource1.Count > 0; 
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        bindingSource1.AddNew();

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.panel1.DataBindings.Add(new Binding("Enabled", this, "HasRecord", false, DataSourceUpdateMode.OnPropertyChanged));
    }

    private void bindingSource1_ListChanged(object sender, ListChangedEventArgs e)
    {
        // Notify
        OnPropertyChanged("HasRecord");
    }

}
相关问题