I have this combobox on a WPF form
Settings.xaml
<ComboBox x:Name="cboKioskType" HorizontalAlignment="Right" Margin="0,0,0,0" SelectedValuePath="Tag">
<ComboBoxItem IsEnabled="False" IsSelected="True" Tag="empty" Content="Select Kiosk Type" />
<ComboBoxItem Tag="spd" Content="SPD"/>
<ComboBoxItem Tag="vendor" Content="Vendor"/>
</ComboBox>
I also have a custom object that is populated from XML, and I'm trying to use the value from that to set my ComboBox Selected
ComputerSetting.cs
namespace Kiosk
{
public class ComputerSetting
{
[XmlAttribute("computer_type")]
public string ComputerType { get; set; }
}
}
Settings.xaml.cs
namespace Kiosk
{
public partial class Settings : Window
{
internal ComputerSetting ComputerSettings = new ComputerSetting();
}
internal void SetSettingsFields()
{
cboKioskType.SelectedItem = this.ComputerSettings.ComputerType;
}
}
The xml works, and the TextBox fields I have on the Settings form all get the values from the XML as expected. But I can't figure out how to get the ComboBox to work properly.
I assume I'm not using the SelectedValuePath on the ComboBox the correct way.
Try This Way
public class ComputerSetting
{
public string ComputerType;
}
public class ComputerList
{
[XmlElement("ComputerSettings")]
public List<ComputerSettings> Computers;
}
var computers = (ComputerList)new XmlSerializer(typeof(ComputerList)).Deserialize(stream);
cboKioskType.ItemsSource = computers.ComputerSettings;
<ComboBox x:Name="cboKioskType" IsReadOnly="False" HorizontalAlignment="Left" IsEditable="True" DisplayMemberPath="ComputerType">
The answer is that I should have used
cboKioskType.SelectedValue = this.ComputerSettings.ComputerType;
not
cboKioskType.SelectedItem = this.ComputerSettings.ComputerType;
NB For this situation data binding isn't appropriate, which is why I'm using a more manual method to set the fields. The code I've given was simplified for this question, so it's obvious that I shouldn't be using binding.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.