Невозможно перейти с одной страницы на новую страницу при отправке значений в WPF C # - PullRequest
0 голосов
/ 29 ноября 2018

В моем MainWindow.xaml.cs я открываю новую страницу (PkmnSelect), используя это:

PkmnSelect pkmnSelect = new PkmnSelect(); 
Content = pkmnSelect;

Затем, когда пользователь выбрал свою команду покемонов на этой странице (PkmnSelect), онможете нажать Пуск.Кнопка «Пуск» имеет следующий код:

Battle battle = new Battle(userPokemon, opponentPokemon);
Content = battle;

Battle - это страница, которую я хочу использовать в качестве входных данных для двух покемонов [], поэтому я создал дополнительный конструктор в Battle, который выглядит следующим образом:

public Battle(Pokemon[] userPkmn, Pokemon[] opponentPkmn) : this()
{
    userPokemon = userPkmn;
    opponentPokemon = opponentPkmn;
}

Это дает мне сообщение об ошибке «Страница может иметь только окно или фрейм в качестве родителя».

Мой вопрос: как правильно передавать значения с одной страницы на другую?Я смотрел везде, и ничего, что я пробовал, не сработало.

РЕДАКТИРОВАТЬ: начало Battle.xaml.cs:

public partial class Battle : Page
{
    Pokemon[] userPokemon;
    Pokemon[] opponentPokemon;

    public Battle()
    {
        InitializeComponent();
        //Some code to hide some xaml stuff and start some music
    }

    public Battle(Pokemon[] userPkmn, Pokemon[] opponentPkmn) : this()
    {
        userPokemon = userPkmn;
        opponentPokemon = opponentPkmn;
    }

1 Ответ

0 голосов
/ 29 ноября 2018

Вы не можете иметь Page внутри Page.

Вместо этого вы должны позволить их общему родительскому компоненту обрабатывать переход, используя события :

Pokemon:

public class Pokemon
{
    public string Name { get; set; }
}

PkmnSelect

<Page x:Class="WpfApp1.PkmnSelect"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:system="clr-namespace:System;assembly=mscorlib"
      Title="PkmnSelect">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <ListBox Name="FirstPokemonList">
            <system:String>Pikachu</system:String>
            <system:String>Raichu</system:String>
            <system:String>Rattata</system:String>
        </ListBox>
        <Label Grid.Column="1" VerticalContentAlignment="Center" FontSize="20" FontWeight="ExtraBold">VS</Label>
        <ListBox Name="SecondPokemonList" Grid.Column="2" Margin="0,1,0,19" Grid.RowSpan="2">
            <system:String>Pikachu</system:String>
            <system:String>Raichu</system:String>
            <system:String>Rattata</system:String>
        </ListBox>
        <Button Click="Button_Click" Grid.Row="1" Grid.ColumnSpan="3">FIGHT!</Button>
    </Grid>
</Page>

public class PokemonsSelectedEventArgs : EventArgs
{
    public Pokemon FirstPokemon { get; set; }
    public Pokemon SecondPokemon { get; set; }
}

public partial class PkmnSelect : Page
{
    public event EventHandler<PokemonsSelectedEventArgs> PokemonsSelected = delegate { };

    public PkmnSelect()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        PokemonsSelected(this, new PokemonsSelectedEventArgs
        {
            FirstPokemon = new Pokemon { Name = (string)FirstPokemonList.SelectedValue },
            SecondPokemon = new Pokemon { Name = (string)SecondPokemonList.SelectedValue }
        });
    }
}

Battle:

<Page x:Class="WpfApp1.Battle"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Title="Battle">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Label HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Content="{Binding UserPokemon.Name}" FontSize="40" FontWeight="ExtraBold"></Label>
        <Label VerticalContentAlignment="Center" FontSize="20" FontWeight="ExtraBold" Grid.Column="1">VS</Label>
        <Label HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Content="{Binding OpponentPokemon.Name}" FontSize="40" FontWeight="ExtraBold" Grid.Column="2"></Label>
    </Grid>
</Page>

public partial class Battle : Page
{
    public Pokemon UserPokemon { get; set; }
    public Pokemon OpponentPokemon { get; set; }

    public Battle()
    {
        InitializeComponent();

        DataContext = this;
    }

    public Battle(Pokemon userPkmn, Pokemon opponentPkmn) : this()
    {
        UserPokemon = userPkmn;
        OpponentPokemon = opponentPkmn;
    }
}

MainWindow:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApp1"
        Title="MainWindow" Height="450" Width="800">
    <local:PkmnSelect PokemonsSelected="PkmnSelect_PokemonsSelected"></local:PkmnSelect>
</Window>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void PkmnSelect_PokemonsSelected(object sender, PokemonsSelectedEventArgs e)
    {
        Content = new Battle(e.FirstPokemon, e.SecondPokemon);
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...