簡體   English   中英

以編程方式設置DataGrid.SelectedItem

[英]Programmatically Set DataGrid.SelectedItem

我有多個存儲唯一ID的DataGrids ,然后是有關該個人,公司等的多列信息。該DataGridTabControl一起存儲,並帶有一個單獨的TabItem ,用於填充有關個人/公司的詳細信息。 當用戶單擊添加時,我想將它們帶回到第一個TabItem ,並自動選擇用戶添加的新項目(個人或公司)。 DataGrids綁定到ObservableCollections

我已經可以使用以下方式設置TabItem了:

tabItem.IsSelected = true

有沒有一種方法,單擊添加后,我設置TabItem ,遍歷DataGrid的項目,找到新項目的ID並將其設置為SelectedItem 當我將其分配給個人/公司時,我會知道該項目的ID。

編輯:我嘗試使用;

CompanyView.MoveCurrentTo(companyDetails);

CompanyView是CollectionViewcompanyDetails是用戶添加的Company的詳細信息,但這不起作用。

您已經說過可以將TabItem設置回去,所以讓我們進一步。

要遍歷DataGrid

int ID=5; //you said you know the ID field

var items = yourDataGrid.Items as ObservableCollection<CompanyModel>;
foreach (CompanyModel m in items)
{
     if (m.Id == ID)
     { 
        yourDataGrid.SelectedItem = item;                                   
        yourDataGrid.ScrollIntoView(yourDataGrid.SelectedItem);
        break;
     }
 }

MVVM模型非常適合此類情況。

如果綁定到集合,則可以通過List.Except()將更改推送到設置器中的集合之前捕獲更改。

由於將DataGrid綁定到ObservableCollection,因此可以為SelectedItem添加附加綁定,並在找到更改並將更改推送到Collection之后手動設置SelectedItem。

回到何時選擇所需的TabItem由您決定。

由於您綁定的是SelectedItem,因此您需要添加

SelectionMode="Single"

NotifyPropertyChanged(); 因為MVVM模型而使用

特性:

private Item _selectedItem;

public Item SelectedItem
{
    get { return _selectedItem; }
    set
    {
        _selectedItem= value;
        NotifyPropertyChanged();
    }
}

private ObservableCollection<Item> _items;

public ObservableCollection<Item> Items
{
    get { return _items; }
    set
    {
        var tempList = value.Except(_items).ToList();

        _addresses = value;

        //if you are 100% sure only one item will be added at a time, you can add .First()
        //edit: please also keep in mind you need to check if there is actually an item that was added. when items are removed, this would also try to change the SelectedItem
        SelectedItem = tempList.First();

        NotifyPropertyChanged();
    }
}

WPF綁定示例:

<DataGrid
    ItemsSource="{Binding Items}"
    SelectionMode="Single"
    SelectedItem="{Binding SelectedItem}"
>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM