Updating SelectedItem of DataGrid

Nov 18, 2010 at 3:46 AM

Hi Michael

I'm having trouble with DataGrids and ListBoxes. If I have a button to create a new item, it adds the item to the list in the DataGrid. I also automatically select that item. The details view for that new selected item comes up, but it doesn't appear selected in the DataGrid/ListBox. The same thing happens if I use a button to go to the first/last item in the DataGrid. They are selected but this isn't represented in the DataGrid.

I don't know if this is a bug or if there is something more I need to do to make it appear selected.

Nov 18, 2010 at 4:27 AM
Edited Nov 18, 2010 at 4:56 AM

Maybe this doesn't work because I'm not using ObservableCollection.

Coordinator
Nov 18, 2010 at 8:49 PM
Edited Nov 18, 2010 at 8:52 PM

No, ObservableCollection is not necessary. In fact, if you return an ObservableCollection, Update Controls will step out of the way. It assumes that you are going to manage ObservableCollections on your own.

It sounds like you need to implement Equals and GetHashCode on your list item. Here's an example of how I write the list/detail pattern. Here's my main view model:

public IEnumerable<OrderSummaryViewModel> PendingOrders
{
    get
    {
        return _company.PendingOrders
            .Select(o => new OrderSummaryViewModel(o));
    }
}

public OrderSummaryViewModel SelectedOrderSummary
{
    get
    {
        return _navigation.SelectedOrder == null
            ? null
            : new OrderSummaryViewModel(_navigation.SelectedOrder);
    }
    set
    {
        _navigation.SelectedOrder = value == null
            ? null
            : value.Order;
    }
}

public OrderDetailsViewModel SelectedOrderDetails
{
    get
    {
        return _navigation.SelectedOrder == null
            ? null
            : new OrderDetailsViewModel(_navigation.SelectedOrder);
    }
}

And here's the OrderSummaryViewModel:

 

public class OrderSummaryViewModel
{
    private Order _order;

    public OrderSummaryViewModel(Order order)
    {
        _order = order;
    }

    public Order Order
    {
        get { return _order; }
    }

    // Properties to bind to in the list box item tempate.

    public override bool Equals(object obj)
    {
        if (obj == this)
            return true;
        OrderSummaryViewModel that = obj as OrderSummaryViewModel;
        if (that == null)
            return false;
        return this._order == that._order;
    }

    public override int GetHashCode()
    {
        return _order.GetHashCode();
    }
}

Without Equals and GetHashCode, the SelectedOrderSummary property would not be equal to a member of the PendingOrders list. I suspect that's what you're running up against.

 

Nov 18, 2010 at 9:50 PM

Hi Michael

You were quite correct! Argh! All this UI stuff is so complicated. There are so many little nuances that I miss. It's slowly coming together though.

Thanks for all your help and suggestions.