Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom equality comparer for WPF ComboBox

When we bind the combobox's SelectedItem to a property, normally it will use the Equals method of the object type to determine the selected item that should be displayed in the ComboBox view. (see this question, for example)

Is it possible to have my own comparer for this, without needing to modify the class' equals method? The reason I don't want to modify the method directly is because the class is also used for business logic and I don't want my equality comparer to affect other things that use the same class

like image 724
Louis Rhys Avatar asked Nov 23 '12 02:11

Louis Rhys


1 Answers

The reason I don't want to modify the method directly is because the class is also used for business logic and I don't want my equality comparer to affect other things that use the same class

This usually indicates a wrapper that is needed:

public class Wrapper<T>
{
    public override string ToString() { ... }

    public override bool Equals(object obj) { ... }

    public T UnderlyingRecord { get; set; }
}

This way you can carry on as normal and only the view will use the wrapper object.

like image 85
Willem Toerien Avatar answered Oct 16 '22 02:10

Willem Toerien