Equin.ApplicationFramework.BindingListView的正確使用情況如下
在創建您的形式:
- 創建BindingListView。稍後將填充要顯示/排序/過濾的項目
- 創建一個BindingSource。
- 創建一個DataGridView。
- 添加列要顯示
後三個步驟可以在Visual Studio的設計師來完成的屬性。如果你這樣做,代碼將在InitializeComponents
。
假設你要顯示的MyType
您的表單/排序/過濾元件將是這樣的:
public class MyForm : Form
{
private BindingListView<MyType> MyItems {get; set;}
public MyForm()
{
InitializeComponent();
this.MyItems = new BindingListView<MyType>(this.components);
// components is created in InitializeComponents
this.MyBindingSource.DataSource = this.MyItems;
this.MyDataGridView.DataSource = this.MyBindingSource;
// assigning the DataPropertyNames of the columns can be done in the designer,
// however doing it the following way helps you to detect errors at compile time
// instead of at run time
this.columnPropertyA = nameof(MyType.PropertyA);
this.columnPropertyB = nameof(MyType.PropertyB);
...
}
你可以不BindingSource
做,你可以直接分配BindingListView
到DataGridView
的DataSource
。排序和篩選仍然有效。但BindingSource
將幫助您訪問當前選定的項目。
private MyType SelectedItem
{
get {return ((ObjectView<MyType>)this.MyBindingSource.Current)?.Object; }
}
private void DisplayItems (IEnumerable<MyType> itemsToDisplay)
{
this.MyItems.DataSource = itemsToDisplay.ToList();
this.MyItems.Refresh(); // this will update the DataGridView
}
private IEnumerable<MyType> DisplayedItems
{
get {return this.MyItems; }
// BindingListview<T> implements IEnumerable<T>
}
這就是全部。您不需要創建特殊功能來對鼠標點擊進行排序。排序將自動完成,包括決定排序順序並顯示正確的排序字形。如果你想以編程方式進行排序:
// sort columnPropertyA in descending order:
this.MyDataGridView.Sort(this.columnPropertyA.ListsortDirection.Descending);
一個關於BindingListView
的好處之一是過濾選項:
// show only items where PropertyA not null:
this.MyItems.ApplyFilter(myItem => myItem.PropertyA != null);
// remove the filter:
this.MyItems.RemoveFilter();
(我如果申請或以後需要刷新()不知道刪除過濾器
什麼是'?.Object' - 爲我引發語法錯誤。沒有'?'工作 –
MyObject?.Myproperty使用空條件運算符(C#6中的新增功能)?請參見https://docs.microsoft .COM/EN-US/DOTNET/CSHARP /語言參考/運營/空有條件operato rs我使用了null條件運算符,因爲如果沒有選擇任何東西,那麼MyBindingSource,Current返回null,在這種情況下我想要一個返回null的對象。或者,您可以在訪問屬性MyBindingSource.Current.Object之前檢查MyBindingSource.Current是否等於null –