Как прокрутить записи в файле XML с помощью кнопок «предыдущий / следующий»? - PullRequest
2 голосов
/ 04 ноября 2011

Я новичок в программировании на C #, так что дальше ...

Я пытаюсь написать приложение для электронных записок в качестве подарка, но я оторвался - мое приложение в настоящее время показывает первую запись XML, ноЯ не знаю, как использовать следующую кнопку, чтобы перейти к следующей записи.Я попытался поэкспериментировать с массивами и массивами, но мне кажется, что я не могу приблизиться к тому, что ищу.Буду очень признателен за любую помощь: -)

Я включу свой код XML и XAML ниже, но я опущу код C #, так как это сделает мой пост слишком длинным.Извините, если какой-либо из приведенных ниже кодов не имеет отношения к вам:

XAML:

    <Grid>
    <Grid.DataContext>
        <XmlDataProvider Source="Data/Memories.xml" XPath="/Memories/Memory" />
    </Grid.DataContext>
    <DockPanel Height="22" Name="dockPanel1" HorizontalAlignment="Stretch" VerticalAlignment="Top" Width="Auto">
        <Menu Height="24" Name="menu1" Width="Auto" DockPanel.Dock="Top" VerticalAlignment="Top">
            <MenuItem Header="_File" >
                <MenuItem Header="Add _New Memory" Name="newMemory" Click="newMemory_Click" />
                <MenuItem Header="_Edit this Memory" Name="editMemory" Click="editMemory_Click" />
                <MenuItem Header="_Delete this Memory" Name="deleteMemory" Click="deleteMemory_Click" />
                <MenuItem Header="_Save Changes" Name="saveMemory" Click="saveMemory_Click" />
                <Separator/>
                <MenuItem Header="E_xit" Name="exit" Click="exit_Click" />
            </MenuItem>
            <MenuItem Header="_Edit" />
            <MenuItem Header="_Help" >
                <MenuItem Header="_About muh program" Name="about" Click="about_Click" />
            </MenuItem>
        </Menu>
    </DockPanel>
    <Button Content="&lt;" Margin="-70,32,0,0" Name="previousButton" Height="22" Width="20" VerticalAlignment="Top" Visibility="{Binding IsEnabled, ElementName=newMemory, Converter={StaticResource VisibleIfTrue}}" />
    <Button Content=">" Height="22" Margin="70,32,0,0" Name="nextButton" Width="20" VerticalAlignment="Top" Visibility="{Binding IsEnabled, ElementName=newMemory, Converter={StaticResource VisibleIfTrue}}" />
    <Button Content="?" Margin="0,32,0,0" Name="RandomButton" Height="22" Width="40" VerticalAlignment="Top" Visibility="{Binding IsEnabled, ElementName=newMemory, Converter={StaticResource VisibleIfTrue}}" />
    <TextBlock Height="30" Width="300" Margin="0,62,0,419" TextAlignment="Center" Text="{Binding XPath=@Title}" FontSize="15" FontWeight="Bold" Name="memoryTitle" />
    <TextBlock Height="30" Width="300" Margin="0,84,0,397" TextAlignment="Center" Text="{Binding XPath=./Date}" FontSize="12" FontWeight="Normal" Name="memoryDate" Panel.ZIndex="1" />
    <TextBlock Height="375" HorizontalAlignment="Right" Margin="0,116,26,20" Name="textOutput" Width="300" TextWrapping="Wrap" TextAlignment="Center" Background="White" Visibility="{Binding IsEnabled, ElementName=newMemory, Converter={StaticResource VisibleIfTrue}}">
        <TextBlock.Text>
            <Binding XPath="./Blurb" />
        </TextBlock.Text>
    </TextBlock>
    <TextBox HorizontalAlignment="Right" Margin="0,116,26,20" Name="textInput" Height="375" Width="300" TextWrapping="Wrap" AcceptsReturn="True" Visibility="{Binding IsEnabled, ElementName=newMemory, Converter={StaticResource VisibleIfNotTrue}}" />
    <Image Height="375" HorizontalAlignment="Center" Margin="-326,94,0,0" Name="imgPhoto" Stretch="Uniform" VerticalAlignment="Center" Width="500" ClipToBounds="False" AllowDrop="False" Source="{Binding XPath=ImageFile}" />
    <Image Height="375" HorizontalAlignment="Center" Margin="-326,94,0,0" Name="imgPhotoNew" Stretch="Uniform" VerticalAlignment="Center" Width="500" ClipToBounds="False" AllowDrop="False" Visibility="{Binding IsEnabled, ElementName=newMemory, Converter={StaticResource VisibleIfNotTrue}}" />
    <Button Content="Done" Height="22" Width="40" Margin="463,32,375,0" Name="doneMemoryButton" VerticalAlignment="Top" Click="doneMemoryButton_Click" Visibility="{Binding IsEnabled, ElementName=newMemory, Converter={StaticResource VisibleIfNotTrue}}" />
    <Button Content="Select Photo" Height="22" Width="75" Margin="377,32,427,0"  Name="selectPhotoButton" VerticalAlignment="Top" HorizontalAlignment="Center" Click="selectPhotoButton_Click" Visibility="{Binding IsEnabled, ElementName=newMemory, Converter={StaticResource VisibleIfNotTrue}}" />
</Grid>

XML:

<Memories>
   <Memory Title="1 Year - Howard Jones!" ID="1">
      <ImageFile>Data/Images/01.jpg</ImageFile>
      <Blurb>We saw Howard Jones perform!!</Blurb>
      <Date>06/11/2010</Date>
   </Memory>
   <Memory Title="Ski Holiday" ID="2">
      <ImageFile>Data/Images/02.jpg</ImageFile>
      <Blurb>Our skiing holiday in Flaine!</Blurb>
      <Date>29/11/2010</Date>
   </Memory>
   <Memory Title="Stinksy's Birthday: Ice Bar!" ID="3">
      <ImageFile>Data/Images/03.jpg</ImageFile>
      <Blurb>Absolut Ice Bar</Blurb>
      <Date>19/12/2010</Date>
   </Memory>
</Memories>

1 Ответ

2 голосов
/ 04 ноября 2011

Я не буду работать с этим кодом, но я могу дать вам простой пример того, как это сделать:

<Window.Resources>
    <XmlDataProvider x:Key="data" Source="Data/Memories.xml" XPath="/Memories/Memory" />
    <CollectionViewSource x:Key="dataCvs" Source="{StaticResource data}" />
</Window.Resources>
<StackPanel>
    <ContentControl Content="{Binding Source={StaticResource dataCvs}}">
        <ContentControl.ContentTemplate>
            <DataTemplate>
                <StackPanel>
                    <Image Source="{Binding XPath=ImageFile}" />
                    <TextBlock Text="{Binding XPath=Blurb}" />
                    <TextBlock Text="{Binding XPath=Date}" />
                </StackPanel>
            </DataTemplate>
        </ContentControl.ContentTemplate>
    </ContentControl>
    <Button Content="Previous" Click="Previous_Click" Tag="{StaticResource dataCvs}" />
    <Button Content="Next" Click="Next_Click" Tag="{StaticResource dataCvs}" />
</StackPanel>

ContentControl привязывается к CurrentItem вида в верхней части коллекции памяти, я передаю CollectionViewSource кнопкам, чтобы я мог изменить текущий элемент при нажатии. (Обычно вы должны использовать Command и передавать вместо него CommandParameter, что чище)

private void Next_Click(object sender, RoutedEventArgs e)
{
    var button = (Button)sender;
    var cvs = (CollectionViewSource)button.Tag;
    cvs.View.MoveCurrentToNext();
}

private void Previous_Click(object sender, RoutedEventArgs e)
{
    var button = (Button)sender;
    var cvs = (CollectionViewSource)button.Tag;
    cvs.View.MoveCurrentToPrevious();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...