簡體   English   中英

檢索數據網格中選定行的數據綁定對象

[英]Retrieve databound object for selected row in datagrid

當前,我正在以這種方式從datagrid(WPF)中檢索所選行的實際數據綁定對象:

private void PointListDataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
    PointItem pointItem = (sender as DataGrid).CurrentItem as PointItem;
}

它有效,但這很不雅致,需要我兩次投射。

Treeview有一個SelectedItemChanged事件,該事件使我可以從事件參數中檢索數據綁定對象,但找不到用於DataGrid的相同方法的方法。

如何檢索所選行的數據綁定對象?

您可以只將PointItem類型的屬性添加到DataContext類(例如,包含DataGrid的Window或Page類),然后將CurrentItem屬性綁定到此屬性。 然后,數據綁定將為您處理轉換,您無需手動進行轉換:

    public PointItem CurrentPointItem
    {
        get { return (PointItem)GetValue(CurrentPointItemProperty); }
        set { SetValue(CurrentPointItemProperty, value); }
    }

    // Using a DependencyProperty as the backing store for CurrentPointItem.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty CurrentPointItemProperty =
        DependencyProperty.Register("CurrentPointItem", typeof(PointItem), typeof(MainWindow), new PropertyMetadata(null));

和您的xaml(當然,您必須將DataGrid或其父項之一的DataContext屬性設置為包含CurrentPointItem屬性的對象):

<DataGrid CurrentItem={Binding CurrentPointItem} />

比您可以這樣編寫事件:

private void PointListDataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
    PointItem pointItem = CurrentPointItem;
    if (pointItem == null)
    {
        //no item selected
    }
}

暫無
暫無

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

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