在WPF表单中,使用C#,如何使用标记

时间:2015-09-29 20:21:10

标签: c# wpf xaml combobox

我在WPF表单上有这个组合框

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

xml工作,我在“设置”表单上的TextBox字段都按预期从XML中获取值。但我无法弄清楚如何让ComboBox正常工作。

我假设我没有正确使用ComboBox上的SelectedValuePath。

2 个答案:

答案 0 :(得分: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">

答案 1 :(得分:0)

答案是我应该使用

cboKioskType.SelectedValue = this.ComputerSettings.ComputerType;

cboKioskType.SelectedItem = this.ComputerSettings.ComputerType;

NB对于这种情况,数据绑定并不合适,这就是我使用更手动的方法设置字段的原因。我已经为这个问题简化了代码,因此很明显我不应该使用绑定。