Как сделать кнопку видимой, если регистрация прошла успешно? - PullRequest
1 голос
/ 28 февраля 2020

Итак, у меня есть простое стартовое окно, в котором находятся такие кнопки, как: «Логин», «Регистрация», «Выход» и, наконец, «Запуск программы».

  • Кнопка «Запуск программы» по умолчанию невидима.

  • Кнопка «Войти» еще не работает, поэтому забудьте об этом.

  • Кнопка «Выход» закрывает программу.

  • Кнопка «Регистрация» открывает новое окно, в котором можно ввести ваше имя пользователя и пароль. Затем он сохраняется в таблице, связанной с SQL -Database.

У меня есть publi c bool, который называется «LogIn», где по умолчанию установлено значение false. Успешно зарегистрировавшись, я установил значение true. В моем Startup.xaml я затем проверяю, является ли bool «LogIn» истинным, если оно истинно, оно должно установить видимость моей кнопки «Start Program» видимой. Но, к сожалению, это не работает.

Заранее спасибо за помощь.

Мой код:

Мой Startup.xaml:


<Window x:Class="MiiUse.Startup"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

        xmlns:local="clr-namespace:MiiUse"
        mc:Ignorable="d"
        Title="Welcome To MiiUse" Height="500" Width="850"
        Style="{StaticResource Startup}"
        StateChanged="MaximizeWindow" ResizeMode="NoResize">

    <Grid>
        <Button Style="{StaticResource RoundButton}" Content="Start Program" HorizontalAlignment="Center" VerticalAlignment="Center" Click="Button_Start" x:Name="StartButton" Visibility="Hidden"/>
        <Button Style="{StaticResource RoundButton}" Content="Exit" HorizontalAlignment="Right"  VerticalAlignment="Bottom" Click="Button_Exit" />
        <Button Style="{StaticResource RoundButton}" Content="Register" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,0,16,0" Click="Button_Register"/>
        <Button Style="{StaticResource RoundButton}" Content="Login" HorizontalAlignment="Right" Margin="0,0,77,0" VerticalAlignment="Top" RenderTransformOrigin="0.379,0.002" Click="Button_Login"/>

    </Grid>
</Window>



Как это выглядит так:

Starting-Window

My Startup.xaml.cs:


using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace MiiUse
{
    /// <summary>
    /// Interaction logic for Startup.xaml
    /// </summary>
    public partial class Startup : Window
    {
        public Startup()
        {
            InitializeComponent();

            Registration registration = new Registration();
            if (registration.LogIn == true)
            {
                StartButton.Visibility = Visibility.Visible;
            }
        }

        private void Button_Start(object sender, RoutedEventArgs e)
        {

            MainWindow mainWindow = new MainWindow();
            this.Close();
            mainWindow.Show();
        }

        private void Button_Exit(object sender, RoutedEventArgs e)
        {
            this.Close();

        }

        private void MaximizeWindow(object sender, EventArgs e)
        {
            if (this.WindowState == WindowState.Maximized)
            {
                this.WindowState = WindowState.Normal;
            }
        }

        private void Button_Register(object sender, RoutedEventArgs e)
        {
            Registration registration = new Registration();
            registration.Show();

        }

        private void Button_Login(object sender, RoutedEventArgs e)
        {

        }
    }
}


My Registration.xaml:

<Window x:Class="MiiUse.Registration"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MiiUse"
        mc:Ignorable="d"
        Title="Registration" Height="320" Width="370">
    <Grid>
        <Label Content="Enter your Username:" HorizontalAlignment="Left" Margin="44,44,0,0" VerticalAlignment="Top"/>
        <Label Content="Enter your Password:" HorizontalAlignment="Left" Margin="44,98,0,0" VerticalAlignment="Top" />
        <Button Content="Submit" HorizontalAlignment="Left" Margin="44,245,0,0" VerticalAlignment="Top" Click="Submit"/>
        <Button Content="Cancel" HorizontalAlignment="Left" Margin="124,245,0,0" VerticalAlignment="Top" Click="Cancel"/>
        <TextBox x:Name="Username" HorizontalAlignment="Left" Margin="44,75,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <PasswordBox x:Name="Password" HorizontalAlignment="Left" Margin="44,129,0,0" VerticalAlignment="Top" Width="120"/>


    </Grid>
</Window>


Как это выглядит:

Registration-Window

My Registration.xaml.cs:


using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace MiiUse
{
    /// <summary>
    /// Interaction logic for Registration.xaml
    /// </summary>
    public partial class Registration : Window
    {
        public Registration()
        {
            InitializeComponent();
        }

        public bool LogIn = false;

        private void Submit(object sender, RoutedEventArgs e)
        {
            string username = Username.Text;
            string password = Password.Password;

            if(Password.Password.Length == 0)
            {
                MessageBox.Show("Password can't be empty!", "Invalid Input!", MessageBoxButton.OK, MessageBoxImage.Error);
                Password.Focus();
            }else if(Username.Text.Length == 0)
            {
                MessageBox.Show("Username can't be empty!", "Invalid Input!", MessageBoxButton.OK, MessageBoxImage.Error);
                Username.Focus();
            }
            else
            {
                using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.connection_String))
                {
                    using SqlCommand sqlCommandGetTemplatesAndDrafts = new SqlCommand(@$"
                    Insert into tbl_Users (Username, Password) values('{username}','{password}')", connection);
                    connection.Open();
                    sqlCommandGetTemplatesAndDrafts.ExecuteNonQuery();
                    connection.Close();
                }
                MessageBox.Show("You were successfully registered, and automatically logged in!", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
                Close();
                LogIn = true;
            }
        }

        private void Cancel(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}


Ответы [ 2 ]

1 голос
/ 28 февраля 2020

Вы не устанавливаете свойство Visibility после открытия окна Registration.

Вы можете отобразить окно Registration как модальное:

private void Button_Register(object sender, RoutedEventArgs e)
{
    Registration registration = new Registration();
    registration.ShowDialog();
    if (registration.LogIn == true)
    {
        StartButton.Visibility = registration.LogIn ? Visibility.Visible : Visibility.Hidden;
    }
}

Также установите LogIn перед , когда вы закроете окно в Submit:

...
LogIn = true;
Close();

Другой вариант - ввести Registration со ссылкой на MainWindow:

private readonly MainWindow _mainWindow;
public Registration(MainWindow mainWindow)
{
    _mainWindow = mainWindow;
    InitializeComponent();
}
...
private void Submit(object sender, RoutedEventArgs e)
{
    ...
    _mainWindow.StartButton.Visibility = Visibility.Visible;
    Close();
...

MainWindow:

private void Button_Register(object sender, RoutedEventArgs e)
{
    Registration registration = new Registration(this);
    registration.Show();
}

Buf Если вы серьезно относитесь к WPF и XAML, вы должны изучить [MVVM].

0 голосов
/ 28 февраля 2020

конвертируйте ваш логин из bool в Visibility, поэтому вместо true или false мы можем упомянуть Visibility.visible или Visibility.hidden. следующим образом:

public Visibility LogIn = Visibility.Hidden;

наконец, свяжите видимость кнопки запуска с этой переменной входа в систему

Так что при успешном завершении SQL:

LogIn = Visibility.visible ;

окончательная привязка:

    <Button Style="{StaticResource RoundButton}" Content="Start Program" HorizontalAlignment="Center" VerticalAlignment="Center" Click="Button_Start" x:Name="StartButton" Visibility="{binding LogIn}"/>

, но этот логин должен быть либо внутри кода, либо для модели View

, но я думаю, что лучший способ сделать это - создать класс publi c с именем helper и сохранить их переменные соединения в нем, так что они доступны во всем приложении

создают свойства:

private Visibility _logIn;
public Visibility LogIn
{
  get => _logIn;
  set
  {
      _logIn= value;
      OnPropertyChanged();
  }
}

, а некоторые из них в вашем приложении инициализируют его скрытым

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...