IEditableCollectionView.AddNew 方法

定义

将新项添加到集合。

public:
 System::Object ^ AddNew();
public object AddNew ();
abstract member AddNew : unit -> obj
Public Function AddNew () As Object

返回

添加到集合中的新项。

示例

以下示例创建一个 Window ,提示用户添加新项。 然后,它调用 AddNew 创建一个新的 对象,并将 的 Window 设置为DataContext该对象。 有关整个示例,请参阅 使用 IEditableCollectionView 示例更改集合

IEditableCollectionView editableCollectionView = 
    itemsControl.Items as IEditableCollectionView; 

if (!editableCollectionView.CanAddNew)
{
    MessageBox.Show("You cannot add items to the list.");
    return;
}

// Create a window that prompts the user to enter a new
// item to sell.
ChangeItemWindow win = new ChangeItemWindow();

//Create a new item to be added to the collection.
win.DataContext = editableCollectionView.AddNew();

// If the user submits the new item, commit the new
// object to the collection.  If the user cancels 
// adding the new item, discard the new item.
if ((bool)win.ShowDialog())
{
    editableCollectionView.CommitNew();
}
else
{
    editableCollectionView.CancelNew();
}
Dim editableCollectionView As IEditableCollectionView = TryCast(itemsControl.Items, IEditableCollectionView)

If Not editableCollectionView.CanAddNew Then
    MessageBox.Show("You cannot add items to the list.")
    Return
End If

' Create a window that prompts the user to enter a new
' item to sell.
Dim win As New ChangeItemWindow()

'Create a new item to be added to the collection.
win.DataContext = editableCollectionView.AddNew()

' If the user submits the new item, commit the new
' object to the collection.  If the user cancels 
' adding the new item, discard the new item.
If CBool(win.ShowDialog()) Then
    editableCollectionView.CommitNew()
Else
    editableCollectionView.CancelNew()
End If

注解

调用 AddNew 将开始添加事务。 应调用 CommitNewCancelNew 以结束添加事务。 新项始终显示在集合视图中。 调用 时 CommitNew ,应用于视图的任何筛选、排序或分组都应用于新项。

适用于