Search code examples
c#wpfdatagridoverridingidentity

DataGrid identity problem when bound to list with overridden IsEqual method


Picture the following scenario: I have a DataGrid which I've bound to a list containing objects. Each object represents a row with various data (name, customer, server name etc.) Now let's say that it's possible to have identical objects or rows (where name, customer, server name etc.) are identical.

When I bind the list to the DataGrid everything works fine and I can move through the grid with my cursor. However, in order to make UnitTests I've overridden the Equals method of the object in question. Like this:

public override bool Equals(object obj2)
{
    ConnectionDestination compareObject = obj2
        as ConnectionDestination;
    if (compareObject == null)
    {
        return false;
    }
    if ((this.Kunde != compareObject.Kunde) ||
        this.Filiale != compareObject.Filiale ||
        this.Bez != compareObject.Bez ||
        this.Username != compareObject.Username ||
        this.Password != compareObject.Password)
    {
        return false;
    }
}
public override int GetHashCode()
{
    return this.Kunde.GetHashCode() ^ this.Bez.GetHashCode() ^
        this.Filiale.GetHashCode() ^ this.Servername.GetHashCode() ^
        this.Username.GetHashCode() ^ this.Password.GetHashCode();
}

Now the problem is that once I have two exactly identical rows and the Equals method is invoked, the DataGrid gets confused and selects multiple rows or it gets even more chaotic as I move through the grid.

Thus the question: Is there a way to make a proper equal comparison to prevent such problems from happening?


Solution

  • The behaviour is correct and follows the logic how all WPF list implements the selection logic. The only way I see to workaround is to wrap the items before using them in the items source.
    If you work with the MVVM pattern, this will lead to a ViewModel per row.

    As a sidenote for the DataGrid: Take also care that the GetHashCode()-Method returns the same value for objects that are equal. Otherwise, selection will also have problems. From your example I do not see if you have overriden GetHashCode(). Since it is mandatory to override GetHashCode() if you override Equals(), this is not a real problem, I only wanted to mention.