簡體   English   中英

如何為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類的deserializeXML方法中,您正在從XML讀取數據並創建一個名為XmlData的新Data對象,它的作用域僅在該方法內,這意味着它已丟失,即使您正在讀取已丟棄的數據也是如此。

其次,您的xml根元素是一個包含Word列表的列表(WordList),每個Word都是您在Data中定義的。 您還需要將Word List定義為WordList類,然后創建XmlSerializer(typeof(WordList));。 我使用xsd.exe將示例.xml轉換為.xsd(模式),然后轉換為c#類。 在這里參考如何將xml轉換為c#類

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

您定義的Data類類似於WordListWord!

最后,您可以將數據上下文設置為WordList.Items.ToList()或ObservableCollection(WordList.Items)

暫無
暫無

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

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