如何为 WPF 应用程序修复此代码?

How can I fix this code for WPF Application?

作为学习资源,我想将 XAML 完成大部分工作的项目转换为后端代码。所以,这是我尝试转换的原始 XAML 代码。

<Page x:Class="EJCSpeechDictionary.ChineseEnglish"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="294.667" d:DesignWidth="444"
    Title="ChineseEnglish" Height="294.667" Width="444">
    <Page.Resources>
        <XmlDataProvider x:Key="XmlData"
                   Source="DictionaryData.xml"
                   XPath="WordList/Word"/>
    </Page.Resources>
    <Grid>
        <Grid.DataContext>
            <XmlDataProvider x:Name="XmlData" Source="DictionaryData.xml" XPath="WordList/Word"/>
        </Grid.DataContext>
        <ListBox Name="listBx" ItemsSource="{Binding XPath=/WordList/Word/Chinese}" IsSynchronizedWithCurrentItem="True" HorizontalAlignment="Left" Height="162" Margin="10,10,0,0" VerticalAlignment="Top" Width="151"/>
        <TextBox IsReadOnly="True" Text="{Binding XPath=../English}" Name="spokenWords" DataContext="{Binding ElementName=listBx, Path=SelectedItem}" HorizontalAlignment="Left" Margin="262,127,0,0" VerticalAlignment="Top" Width="171" Height="20"/>
        <Button Content="Speak" Name="speakBtn" HorizontalAlignment="Left" Margin="262,152,0,0" VerticalAlignment="Top" Width="75" Click="speakBtn_Click"/>

    </Grid>
</Page>

到目前为止,我已经尝试使用 Observable 集合并得到了 C# 编程大神告诉我不的结果! 当我 运行 程序时,我的列表框完全是空的。 这是我到目前为止所做的代码:

    public class Data : INotifyPropertyChanged
    {
        private string chinese;
        private string pinyin;
        private string english;
        private const string filePath = @"https://onedrive.live.com/redir?resid=20c5e1cad5eac97f!22900&authkey=!AAjCLv_ozEqrdAY&ithint=file%2cxml";

        public string Chinese
        {
            get 
            { return this.chinese; }
            set
            {
                if (this.chinese != value)
                {
                    this.chinese = value;
                    this.NotifyPropertyChanged("Chinese");
                }
            }
        }
        public string Pinyin
        {
            get { return this.pinyin; }
            set
            {
                if (this.pinyin != value)
                {
                    this.pinyin = value;
                    this.NotifyPropertyChanged("Pinyin");
                }
            }
        }

        public string English
        {
            get { return this.english; }
            set
            {
                if (this.english != value)
                {
                    this.english = value;
                    this.NotifyPropertyChanged("English");
                }
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }

        public void deserializeXML()
        {
            if (File.Exists(filePath))
            {
                XmlSerializer deserializer = new XmlSerializer(typeof(Data));
                TextReader reader = new StreamReader(filePath);
                object obj = deserializer.Deserialize(reader);
                Data XmlData = (Data)obj;
                reader.Close();
            }
        }
    }
}


    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private ObservableCollection<Data> calledData = new ObservableCollection<Data>();

        public MainWindow()
        {
            InitializeComponent();

            Data data = new Data();
            data.deserializeXML();
            listBox.ItemsSource = data.Chinese;
        }
    }
}

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--This is a generated XML File-->
<WordList>
  <Word>
    <English>able</English>
    <Pinyin>Néng</Pinyin>
    <Chinese>能</Chinese>
  </Word>
  <Word>
    <English>aboard</English>
    <Pinyin>Chuánshàng</Pinyin>
    <Chinese>船上</Chinese>
  </Word>
  <Word>
    <English>about</English>
    <Pinyin>Dàyuē</Pinyin>
    <Chinese>大约</Chinese>
  </Word>
  <Word>
    <English>above</English>
    <Pinyin>Yǐshàng</Pinyin>
    <Chinese>以上</Chinese>
  </Word>
  <Word>
    <English>accept</English>
    <Pinyin>Jiēshòu</Pinyin>
    <Chinese>接受</Chinese>
  </Word>
  </WordList>

因此,就目前情况而言,我对我在代码中做错了什么感到茫然。任何指向正确方向的指示(哈!我用双关语把自己搞砸了)将不胜感激。

首先,在 Data class 中的反序列化 XML 方法中,您正在从 XML 读取数据并创建一个名为 XmlData 的新 Data 对象,它的范围仅在该方法意味着它丢失了,即使您正在读取它被丢弃的数据。

其次,您的 xml 根元素是一个包含单词列表的列表 (WordList),每个单词都是您在数据中定义的。您还需要将 Word List 定义为 class WordList,然后创建一个 XmlSerializer(typeof(WordList));我使用 xsd.exe 将您的示例 .xml 转换为 .xsd(架构),然后转换为 c# class。 Refer here on how to convert xml to c# class

using System.Xml.Serialization;

// 
// This source code was auto-generated by xsd, Version=4.0.30319.1.
// 

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class WordList {

    private WordListWord[] itemsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Word", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public WordListWord[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class WordListWord {

    private string englishField;

    private string pinyinField;

    private string chineseField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string English {
        get {
            return this.englishField;
        }
        set {
            this.englishField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Pinyin {
        get {
            return this.pinyinField;
        }
        set {
            this.pinyinField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Chinese {
        get {
            return this.chineseField;
        }
        set {
            this.chineseField = value;
        }
    }
}

您定义的数据 class 与 WordListWord 相似!

最后,您可以将数据上下文设置为 WordList.Items.ToList() 或 ObservableCollection(WordList.Items)