2015-09-29 15 views
0

我有一个WPF窗体上的此组合框在WPF的形​​式,使用C#,我怎么使用标签

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> 

我也有一个自定义的对象,它是设置一个组合框从XML填充,和我想要使用的值从设置我的ComboBox中选定

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; 
    } 
} 

的XML的作品,并在TextBox领域我对设置形成所有从XML获取值如预期。但我无法弄清楚如何让ComboBox正常工作。

我假设我没有以正确的方式在ComboBox上使用SelectedValuePath。

+0

事实上,你没有正确使用'SelectedValuePath'。为了它的工作,你必须首先为你的ComboBox设置数据绑定。如果你之前没有这样做,我会建议[教程](http://www.codeproject.com/Articles/301678/Step-by-Step-WPF-Data-Binding-with-Comboboxes)。 – vesan

回答

0

答案是,我应该使用

cboKioskType.SelectedValue = this.ComputerSettings.ComputerType; 

cboKioskType.SelectedItem = this.ComputerSettings.ComputerType; 

NB对于这种情况,数据绑定是不合适的,这是为什么我使用更手动的方法来设置字段。我给出的代码对这个问题进行了简化,所以显然我不应该使用绑定。

0

试试这个方法

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">