2015-09-29 16 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">