c# - ComboBox not autoselecting initial value -


i have combobox bound list of people in simple viewmodel. selectedperson set in constructor of viewmodel, when run application, combobox not set initial value. doing wrong?

notice 2 instances of myperson class should considered equal when have same id.

important: cannot modify myperson override equals (it's third party).

the option i've seen far user adapter pattern wrap instances of class , implement custom equals method there.

i feel there should better method native wpf match items list kind of "key". in case, list of items , selected item come different sources, , that's why have id property acting primary key.

please, take @ code, i've played selectedvalue , selectedvaluepath, nothing works.

<window x:class="test.mainwindow"         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"         xmlns:vm="clr-namespace:test"         mc:ignorable="d"         x:name="root"         title="mainwindow" height="350" width="525">     <window.datacontext>         <vm:mainviewmodel />     </window.datacontext>     <combobox itemssource="{binding people}" selecteditem="{binding selectedperson}" selectedvaluepath="id"               displaymemberpath="name"               selectedvalue="{binding selectedperson}" /> </window> 

and viewmodel datacontext:

public class mainviewmodel {     public mainviewmodel()     {         selectedperson = new myperson { name = "mary", id = 1 };     }      public myperson selectedperson { get; set; }      public ienumerable<myperson> people { get; } = new list<myperson>()     {         new myperson() {name = "mary", id = 1 },         new myperson() {name = "john", id = 2 },     }; }  public class myperson {     public string name { get; set; }     public int id { get; set; } } 

the problem new object create here

selectedperson = new myperson { name = "mary", id = 1 }; 

isnt' same in list equals method return false in cases!

as else suggested, have real object in list doing this:

public mainviewmodel(){    selectedperson = people.first(x=> x.name.equals("mary")); //or: x.id == 1 } 

but there solution: can override equals function in myperson class, every myperson instance same name and/or id indeed seen same person.

edit

as you're using viewmodels in project, better if had viewmodel mypersonclass too. solve problems and make design better!


Comments

Popular posts from this blog

Android volley - avoid multiple requests of the same kind to the server? -

magento2 - Magento 2 admin grid add filter to collection -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -