C# - Can I Data Bind between a value and an expression?

喜你入骨 提交于 2019-12-13 04:13:36

问题


I have a List and a Button. When the Lists Count == 0, I would like the button Visibility to = false.

How do I do this using Data Binding?

Thanks in advance,

Added
I have asked this so that I can try to avoid checking the Count on the list in code every time I add or remove an item to or from the list. But if there is no solution then I will continue to do it that way.


回答1:


Create a DTO (Data Transfer Object) that exposes all your data that you intend to bind to UI elements. Create a property in the DTO (with an appropriate name):

public bool ButtonVisible
{
   get { return myListCount != 0; }
}

Add a BindingSource to your form and set it's DataSource to your DTO type.

Click on the Button, goto Properties. Expand the DataBindings node, and click Advanced.

Scroll down the list in the left hand pane, and select Visible. Set it's binding to your property exposed vis the BindingSource..




回答2:


As the question is currently worded, it doesn't sound like it has anything to do w/ DataBind.

If we have a list -- doesn't matter whether it's populated via code or bound to a data source -- we can set the button's visibility based on the count. e.g.

List<string> somelist = new List<string>();
somelist.Add("string1");
somelist.Add("string2");
Button1.Visible = somelist.Count > 0 ? true : false;



回答3:


I think you want to be using the CurrencyManager and the BindingContext of the control.

http://www.akadia.com/services/dotnet_databinding.html#CurrencyManager




回答4:


The General Answer

Write an event handler and register it with your list-control's bindings object

A Specific Example

class MyForm : Form {
protected Button myButton;
BindingSource myBindingSource;
DataGridView dgv;

public MyForm(List someList) {
    myBindingSource = new BindingSource();
    dgv = new DataGridView();
    this.myButton = new Button();
    this.Controls.Add(myButton);
    this.Controls.Add(dgv);

    myBindingSource.DataSource = someList;
    dgv.DataSource = myBindingSource;

    dgv.DataSource.ListChanged += new ListChangedEventHandler (ListEmptyDisableButton);
}

protected void ListEmptyDisableButton (object sender, ListChangedEventArgs e) {
    this.myButton.Visible = this.dgv.RowCount <= 0 ? false : true;          
}

}

PS - I'd vote down the favorite answer. A Data Transfer Object (DTO) misses the whole point and functionality of .NET Binding architechture



来源:https://stackoverflow.com/questions/1188611/c-sharp-can-i-data-bind-between-a-value-and-an-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!