我一直在做一些研究,基本上是空洞的。我认为这可能很容易理解,但远远超出我目前的知识。这是关于两个文本框。
我想拥有它所以我可以在searchText框中搜索一个单词,翻译的文本将出现在searchResults文本框中。 (xml文件位于https://www.dropbox.com/s/jgw84kqj2k1bwq1/JapaneseEnglishData.xml?dl=0。但是,帖子的底部是它的一个示例)。有没有人对如何实现这一目标有任何见解?
<Window x:Class="BeginnersJapanese.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<XmlDataProvider x:Key="XmlData"
Source="https://www.dropbox.com/s/jgw84kqj2k1bwq1/JapaneseEnglishData.xml?dl=1"
XPath="WordList/Word"/>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding Source={StaticResource XmlData}}" DisplayMemberPath="English" HorizontalAlignment="Left" Height="299" Margin="10,10,0,0" VerticalAlignment="Top" Width="179"/>
<TextBox Name="searchBox" HorizontalAlignment="Left" Height="23" Margin="256,41,0,0" TextWrapping="Wrap" Text="{Binding Path=WordList/Word,BindsDirectlyToSource=True}" VerticalAlignment="Top" Width="142"/>
<Label Content="SearchBox" HorizontalAlignment="Left" Margin="287,10,0,0" VerticalAlignment="Top"/>
<Button Content="Search" Name="searchButton" HorizontalAlignment="Left" Margin="256,207,0,0" VerticalAlignment="Top" Width="142" Height="36" Click="searchButton_Click"/>
<Button Content="Speak" Name="speakButton" HorizontalAlignment="Left" Margin="256,273,0,0" VerticalAlignment="Top" Width="142" Height="36" Click="speakButton_Click"/>
<TextBox Name="searchResult" HorizontalAlignment="Left" Height="23" Margin="256,162,0,0" TextWrapping="Wrap" Text="{Binding Path=searchBox}" IsReadOnly="True" VerticalAlignment="Top" Width="142"/>
</Grid>
</Window>
XML文件的示例。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--This is a generated XML File-->
<WordList>
<Word>
<English>Me</English>
<Romaji>boku</Romaji>
<Kanji>ぼく</Kanji>
</Word>
<Word>
<English>I</English>
<Romaji>boku</Romaji>
<Kanji>ぼく</Kanji>
</Word>
</WordList>
答案 0 :(得分:1)
您需要设置窗口或网格的DataContext才能使绑定生效。This可能会有所帮助。
像这样:<Window
xmlns:local="clr-namespace:MyNamespace"
Window>
<Window.Resources>
<local:MyClass x:Key="MyClass">
</Window.Resources>
<Grid DataContext={StaticResource MyClass}>
...
MyClass的实现:
public class MyClass : INotifyPropertyChanged
{
private string _wordlist;
private string _searchBox;
public string WordList
{
get
{
return _wordlist;
}
set
{
_wordlist = value;
RaisePropertyChanged("WordList");
}
}
public string searchBox
{
get
{
return _searchBox;
}
set
{
_searchBox= value;
RaisePropertyChanged("searchBox");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if(PropertyChanged != null)
PropertyChanged(this, propertyName);
}
}
您可能需要在setter中使用一些额外的逻辑来使用XML进行翻译。 另外,将TextBoxes的UpdateSourceTrigger设置为PropertyChanged:
<TextBox Text={Binding Path=WordList, UpdatesourceTrigger=PropertyChanged} ... />
<TextBox Text={Binding Path=searchBox, UpdateSourceTrigger=PropertyChanged} ... />
我希望这可以让您了解如何获得理想的行为。