C # WPF: не удается подключить texbox.Text к метке. Содержание через класс - PullRequest
0 голосов
/ 03 ноября 2019

Почему это не работает. Я хочу создать пользовательский ввод с текстовым полем в UserInputPage и отобразить его на метке в UserLabelPage, но я получаю сообщение об ошибке FirstUserLabel = null. Как я могу это исправить или я делаю это неправильно? Заранее спасибо за ваше время.

Дирк

App.xaml.cs:

namespace PlayertoLabeltest
{

    public partial class App : Application
    {
        public static MainWindow ParentWindowRef;
    }
}

MainWindow.xaml:

<Grid>
        <DockPanel>
            <Frame x:Name="ParentFrame" NavigationUIVisibility="Hidden"/>
        </DockPanel>
</Grid>

MainWindow.xaml.cs:

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

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            App.ParentWindowRef = this;
            this.ParentFrame.Navigate(new UserInputPage());
        }
    }

UserInputPage.xaml:

 <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>

        <TextBox x:Name="singlePlayer_Input" Grid.Row="1" Grid.Column="1" Width="150" Height="30" HorizontalAlignment="Center" VerticalAlignment="Center"/>
        <TextBox Grid.Row="1" Grid.Column="2" Width="150" Height="30" HorizontalAlignment="Center" VerticalAlignment="Center"/>

        <Button Click="UserInputToLabel_Click" Grid.Row="3" Grid.Column="3" Width="100" Height="50" Content="Click Here"/>
    </Grid>

UserInputPage.xaml.cs:

 public partial class UserInputPage : Page
    {
        private Player FirstPlayer_Input;
        private TextBox SinglePlayer_TextBox;

        public UserInputPage()
        {
            InitializeComponent();
        }

        public void UserInputToLabel_Click(object sender, RoutedEventArgs e)
        {
            SinglePlayer_TextBox = singlePlayer_Input;
            //System.Diagnostics.Debug.WriteLine(singlePlayer_Input.Text);
            FirstPlayer_Input = new Player(SinglePlayer_TextBox.Text);
            FirstPlayer_Input.PlayertoLabel();
            App.ParentWindowRef.ParentFrame.Navigate(new UserLabelPage());
        }
    }

UserLabelPage.xaml:

<Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>

        <Label x:Name="singlePlayer_Label" Content="" Grid.Row="1" Grid.Column="1" Width="150" Height="30" HorizontalAlignment="Center" VerticalAlignment="Center"/>
    </Grid>

UserLabelPage.xaml.cs:

 public partial class UserLabelPage : Page
    {
        private Player FirstPlayer_Label;

        public UserLabelPage()
        {
            InitializeComponent();
            FirstPlayer_Label = new Player(singlePlayer_Label);
        }
    }

Player.cs:

 class Player
    {
        private string FirstUser_Input;
        private Label FirstUser_Label;

        public Player(string text)
        {
            FirstUser_Input = text;
            System.Diagnostics.Debug.WriteLine(FirstUser_Input);
        }

        public Player(Label FirstUser)
        {
            FirstUser_Label = FirstUser; //This one gives FirstUser_Label = null
            //FirstUser_Label.Content = "Rubeus Hagrid"; //This One works
            PlayertoLabel();
        }

        public void PlayertoLabel()
        {
            FirstUser_Label.Content = FirstUser_Input;
            System.Diagnostics.Debug.WriteLine(FirstUser_Input);        
        }
    }

1 Ответ

1 голос
/ 03 ноября 2019

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

Тем не менее, пожалуйста, найдите ответ на свой вопрос ниже

Я считаю, что ошибка происходит внутри вашего UserInputPage.xaml.cs:

FirstPlayer_Input = new Player(SinglePlayer_TextBox.Text);

Внутри вашего класса игрока переменная private Label FirstUser_Label; не инициируется в одномконструктора (public Player(string text)).

Итак, запустите его, как показано ниже,

 `public Player(string text)
    {
        FirstUser_Input = text;
        FirstUser_Label = new Label(); //This line ensures that the FirstUser_Label is not null. It has a empty label value by default.
        System.Diagnostics.Debug.WriteLine(FirstUser_Input);
    }`

Примечание: сам код не проверял.

Обновление: 2019-11-04 Примечание: приведенный ниже код не является чистым. Я хотел бы повторить, что лучше использовать привязку данных и уведомлять об изменениях свойств.

Сделайте вашу метку такой же статической, как показано ниже.

class Player
{
    private string FirstUser_Input;
    private static Label FirstUser_Label; //Making the variable as static

Затем, когда инициализируется ваша страница метки, изменитекод, указанный ниже, для доступа к статическому свойству

public partial class UserLabelPage : Page
{
    private Player FirstPlayer_Label;

    public UserLabelPage()
    {
        InitializeComponent();
        singlePlayer_Label.content = Player.FirstUser_Label.content; //singlePlayer_Lable is the x:name of the xaml object. Setting the object's content while initializing the component.
    }
}

Примечание. Код не проверялся. Но, по теории, это должно работать нормально.

...