【问题标题】:Trying to populate a combobox in winrt xaml from xml file尝试从 xml 文件填充 winrt xaml 中的组合框
【发布时间】:2014-09-29 18:05:26
【问题描述】:

我正在尝试使用 xml 文件中的数据填充下拉列表我确定我已经关闭了,因为智能感知显示 XML 文件中的数据但是当我尝试将它绑定到组合框时,我得到每个条目有数据类型但没有数据。

public void PopPrograms()
{
    //string picprgrmsXMLPath = Path.Combine(Package.Current.InstalledLocation.Path, "Assets/PicPrograms.xml");
    string picprgrmsXMLPath = Path.Combine(Windows.Storage.ApplicationData.Current.RoamingFolder.Path, "PicPrograms.xml");
    //string picprgrmsXMLPath = @"C:\temp\PicPrograms.xml";
    XDocument loadedData = XDocument.Load(picprgrmsXMLPath);

    var data = from query in loadedData.Descendants("Node")
    select new PicPrograms
    {
        //ProgramID = (string)query.Element("pID"),
        ProgramName = (string)query.Element("pName"),
    };
    cbProgram.ItemsSource = data;

现在这是我的 xaml:

<ComboBox x:Name="cbProgram" ItemsSource="{Binding}" HorizontalAlignment="Left" 
          Margin="55,115,0,0" VerticalAlignment="Top" Width="215" Height="32" 
          SelectionChanged="cbProgram_SelectionChanged" Grid.RowSpan="2"/>

我确定我在这里遗漏了一些东西,但只是不知道它是什么。

这是 xml 文档的 sn-p:

<Programs>
  <Node>
    <pID>9930FA1A-A59E-4F78-8AFF-2E07AD4C1CD8</pID>
    <pName>Black and Gold</pName>
  </Node>
  <Node>
    <pID>23B4263C-4BF2-4EC3-AD99-17BCD6301189</pID>
    <pName>Darren Hawkins Pic Review</pName>
  </Node>

生成的组合框为每个元素显示相同的内容:

CameraCapture.CapturePhoto+PicProgram

【问题讨论】:

  • 请发布您的ToString 方法PicProgram 和您的ItemTemplate
  • 抱歉不知道你在说什么
  • 你在PicProgram中有override string ToString()吗?

标签: c# xml xaml windows-runtime


【解决方案1】:

为了告诉ComboBox 控件要显示什么,您需要设置它的DisplayMemberPathItemTemplate。 (否则它会在对象上调用ToString(),默认情况下会返回类型名称,正如您所注意到的。)

例如:

<ComboBox x:Name="cbProgram" DisplayMemberPath="ProgramName" ... 

或者:

<ComboBox x:Name="cbProgram" ...>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding ProgramName}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

【讨论】:

    猜你喜欢
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多