簡體   English   中英

在WPF中將ComboBox綁定到XML

[英]ComboBox Binding to XML in WPF

我知道這個問題已經死了,但是我嘗試了很多發現的建議答案,當我在VS2013中啟動WPF時,組合框仍然沒有出現。 來了 我有一個名為People.xml的XML文檔,其格式如下:

<?xml version="1.0" encoding="utf-8"?>
<People>
  <Person>
    <personName>John Doe</personName>
    <personEmail>someone@yahoo.com</personEmail>
    <personReports>List of reports they get go here.</personReports>
</Person>

在應用程序的App.xml部分中,我將此作為資源:

<XmlDataProvider x:Key="People" Source="\DataSources\People.xml" XPath="People" IsInitialLoadEnabled="True" />

然后,在組合框的XAML中,我將其列出為:

<ComboBox x:Name="employeeNameBox" IsReadOnly="False" HorizontalAlignment="Left" IsEditable="True" ItemsSource="{Binding Source={StaticResource People}, XPath=./Person/personName}">

我想要了解的是在組合框中填充XML文檔中的所有personName元素。

再次,我嘗試了幾種不同的方法來嘗試加載它,並且組合框始終顯示為空。 我對數據綁定結構和WPF相對較新,所以我能得到的任何幫助都會很棒。

謝謝!

對於我來說,最簡單的方法是XmlSerializer

public class Person
{
    public string personName;
    public string personEmail;
    public string personReports;
}

public class People
{
    [XmlElement("Person")]
    public List<Person> Persons;
}

加載數據:

var people = (People)new XmlSerializer(typeof(People)).Deserialize(stream);
employeeNameBox.ItemsSource = people.Persons;

ComboBox代碼:

<ComboBox x:Name="employeeNameBox" IsReadOnly="False" HorizontalAlignment="Left" IsEditable="True" DisplayMemberPath="personName">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM