windows store apps - XAML ComboBox default SelectedIndex is not shown -
i have combobox values, , want have 2 things working @ once.
here combobox , want show 10 default value , bind double? distance property.
<combobox grid.row="5" grid.column="1" selectedindex="1" selectedvalue="{binding distance, mode=twoway, converter={staticresource stringtodoubleconverter}}"> <comboboxitem>1</comboboxitem> <comboboxitem isselected="true">10</comboboxitem> <comboboxitem>100</comboboxitem> <comboboxitem>1000</comboboxitem> </combobox>
and here converter:
public class stringtodoubleconverter : ivalueconverter { public object convert(object value, type targettype, object parameter, string language) { return null; } public object convertback(object value, type targettype, object parameter, string language) { comboboxitem item = value comboboxitem; if (item != null) { double d; if (double.tryparse(item.content.tostring(), out d)) return d; } return null; } }
the problem in code, selected item 10 not show @ start of application. if remove line converter, show selected item 10, then, can't bind double? distance property. dont want write code behind it, such as: convert.todouble(combobox1.selectedvalue)...
what can make both things work?
you need populate combo box items viewmodel. should not use selectedvalue
property, instead of should use selecteditem
. see below given code.
xaml
<combobox x:name="cmb" itemssource="{binding distancecollection}" selecteditem="{binding distance, converter={staticresource stringtodoubleconverter}, mode=twoway}"/>
viewmodel
public class viewmodel : inotifypropertychanged { public viewmodel() { distancecollection = new observablecollection<string> { "1", "10", "100", "1000" }; distance = double.parse(distancecollection[1].tostring()); } public observablecollection<string> distancecollection { get; set; } private double _distance; public double distance { { return _distance; } set { _distance = value; onpropertychanged("distance"); } } public event propertychangedeventhandler propertychanged; protected void onpropertychanged(string propertyname = null) { var eventhandler = this.propertychanged; if (eventhandler != null) { eventhandler(this, new propertychangedeventargs(propertyname)); } } }
converter
public class stringtodoubleconverter : ivalueconverter { public object convert(object value, type targettype, object parameter, string language) { return value.tostring(); } public object convertback(object value, type targettype, object parameter, string language) { string item = value string; if (!string.isnullorwhitespace(item)) { double d; if (double.tryparse(item, out d)) return d; } return null; } }
Comments
Post a Comment