• Najnowsze pytania
  • Bez odpowiedzi
  • Zadaj pytanie
  • Kategorie
  • Tagi
  • Zdobyte punkty
  • Ekipa ninja
  • IRC
  • FAQ
  • Regulamin
  • Książki warte uwagi

Wzorzec MVVM - Nie znaleziono elementu DataContext dla powiązania

Object Storage Arubacloud
0 głosów
123 wizyt
pytanie zadane 12 grudnia 2023 w C# przez MisticVoid Początkujący (490 p.)

Piszę aktualnie projekt za pomocą wzorca MVVM i napotkałem pewien błąd: 
"Nie znaleziono elementu DataContext dla powiązania (i jakiś Binding)". Nie jestem pewien czemu nie działają te bindingi ponieważ pierwszy raz piszę za pomocą tego wzorca. Oto mój kod:
Strona rejestracji Xaml oraz Cs:

<Page x:Class="WorkApp.MVVM.Pages.RegisterPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:local="clr-namespace:WorkApp.MVVM.Pages"
      mc:Ignorable="d" 
      d:DesignHeight="600" d:DesignWidth="900"
      Title="RegisterPage">
    
    <Border CornerRadius="20"
        Background="#366bd6">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="200"/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>

            <Grid.RowDefinitions>
                <RowDefinition Height="75"/>
                <RowDefinition />
            </Grid.RowDefinitions>


            <Label Content="Work"
               HorizontalContentAlignment="Center"
               VerticalContentAlignment="Center"
               FontSize="30"
                   Background="#325ea8"
               />

            <Label Content="Register"
               HorizontalContentAlignment="Center"
               VerticalContentAlignment="Center"
               FontSize="30"
               Grid.Column="1"
               Background="#325ea8"
               />


            <StackPanel Grid.Row="1" 
              Grid.Column="0" 
              Margin="10"
              Grid.ColumnSpan="2"
              >
                <StackPanel>
                    <Label HorizontalAlignment="Center" Content="Name" Foreground="White" FontSize="20"/>
                    <TextBox Style="{StaticResource LoginRegisterTextBoxTheme}" Margin="0,0,0,10" Text="{Binding Name}"/>
                </StackPanel>

                <StackPanel>
                    <Label HorizontalAlignment="Center" Content="Surname" Foreground="White" FontSize="20"/>
                    <TextBox Style="{StaticResource LoginRegisterTextBoxTheme}" Margin="0,0,0,10" Text="{Binding Surname}"/>
                </StackPanel>


                <StackPanel>
                    <Label HorizontalAlignment="Center" Content="Email" Foreground="White" FontSize="20"/>
                    <TextBox Style="{StaticResource LoginRegisterTextBoxTheme}" Margin="0,0,0,10" Text="{Binding Email}"/>
                </StackPanel>


                <StackPanel>
                    <Label HorizontalAlignment="Center" Content="Password" Foreground="White" FontSize="20"/>
                    <TextBox Style="{StaticResource LoginRegisterTextBoxTheme}" Text="{Binding PasswordHash}"/>
                </StackPanel>


                <StackPanel>
                    <Label HorizontalAlignment="Center" Content="Repeat password" Foreground="White" FontSize="20"/>
                    <TextBox Style="{StaticResource LoginRegisterTextBoxTheme}" Margin="0,0,0,10"/>
                </StackPanel>

                <StackPanel>
                    <Button Style="{StaticResource LoginLogoutButtonTheme}" Content="Register" FontSize="20" Width="200" Background="#325ea8" Click="LoginAndBackToMainPage" Command="{Binding AddNewUserCommand}"/>

                    <Button Style="{StaticResource LoginLogoutButtonTheme}" Content="Do you have account? Login now!"  FontSize="20" Width="200" Background="#325ea8" Click="GoToLoginrPage"/>

                    <Button Style="{StaticResource LoginLogoutButtonTheme}" Content="Back to Main Page" FontSize="20" Width="200" Background="#325ea8" Click="BackGoMainPage"/>
                </StackPanel>

            </StackPanel>
        </Grid>
    </Border>
</Page>

 

using WorkApp.MVVM.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Navigation;
using System.Windows.Shapes;

namespace WorkApp.MVVM.Pages
{
    /// <summary>
    /// Logika interakcji dla klasy RegisterPage.xaml
    /// </summary>
    public partial class RegisterPage : Page
    {
        public RegisterPage()
        {
            InitializeComponent();
            AddNewUser newUser = new();
            DataContext = newUser;
        }

        private void LoginAndBackToMainPage(object sender, RoutedEventArgs e)
        {

        }

        private void GoToRegisterPage(object sender, RoutedEventArgs e)
        {

        }

        private void BackGoMainPage(object sender, RoutedEventArgs e)
        {
            if (App.Current.MainWindow is MainWindow mainWindow)
            {
                mainWindow.ChangePage(new MainPage());
            }
        }

        private void GoToLoginrPage(object sender, RoutedEventArgs e)
        {
            if (App.Current.MainWindow is MainWindow mainWindow)
            {
                mainWindow.ChangePage(new LoginPage());
            }
        }
    }
}

Folder "Model" klasa "UserManager":

using Microsoft.Data.Sqlite;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WorkApp.MVVM.Model
{
    public class UserManager
    {
        public static void InsertUserData(Users user)
        {
            string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "work.db");

            using (var db = new SqliteConnection($"Filename={dbPath}"))
            {
                db.Open();
                var insertCommand = new SqliteCommand();
                insertCommand.Connection = db;

                insertCommand.CommandText = "INSERT INTO users VALUES(NULL, @Name, @Surname, NULL ,@Email, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, @Password, NULL, 0);";
                insertCommand.Parameters.AddWithValue("@Name", user.Name);
                insertCommand.Parameters.AddWithValue("@Surname", user.Surname);
                insertCommand.Parameters.AddWithValue("@Email", user.Email);
                insertCommand.Parameters.AddWithValue("@Password", user.PasswordHash);
                insertCommand.ExecuteReader();
            }
        }

    }
}

Folder "ViewModel" klasa "AddNewUser":

using WorkApp.MVVM.Commands;
using WorkApp.MVVM.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace WorkApp.MVVM.ViewModel
{
    public class AddNewUser
    {
        public ICommand AddNewUserCommand { get; set; }


        public string _Name { get; set; }
        public string _Surname { get; set; }
        public string _Email { get; set; }
        public string _PasswordHash { get; set; }

        public AddNewUser() 
        {
            AddNewUserCommand = new RelayCommand(AddUser, CanAddUser);
        }

        private bool CanAddUser(object obj)
        {
            return true;
        }

        private void AddUser(object obj)
        {
            Users users = new(){
                Name = _Name, 
                Surname = _Surname, 
                Email = _Email, 
                PasswordHash = _PasswordHash
            };

            UserManager.InsertUserData(users);
        }
    }
}

Folder "Commands" klasa "RelayCommand":

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace WorkApp.MVVM.Commands
{
    public class RelayCommand : ICommand
    {
        public event EventHandler? CanExecuteChanged;

        private Action<object> _Excute {  get; set; }
        private Predicate<object> _CanExcute { get; set; }

        public RelayCommand(Action<object> executeMethod, Predicate<object> CanExcuteMethod) 
        { 
            _Excute = executeMethod;
            _CanExcute = CanExcuteMethod;
        }

        public bool CanExecute(object? parameter)
        {
            return _CanExcute(parameter);
        }

        public void Execute(object? parameter)
        {
            _Excute(parameter);
        }
    }
}

z góry dziękuję za pomoc smiley.

komentarz 12 grudnia 2023 przez Velta Maniak (52,370 p.)
Dograj sobie Dappera. Nie ma co się męczyć z parametrami zapytań. :D
komentarz 12 grudnia 2023 przez MisticVoid Początkujący (490 p.)

Dziękuję za podpowiedźsmiley. Z pewnością skorzystam z tego rozszerzenia tylko nie wiem czy rozwiązuje ono mój problem.

1 odpowiedź

0 głosów
odpowiedź 21 grudnia 2023 przez Szabranigdo Obywatel (1,370 p.)

Podpowiedź. Sprawdź do jakich właściwości bindujesz a jakie masz we viewModel. Same właściwości proponuje robić 

 private int myVar;
 public int MyProperty
 {
     get { return myVar; }
     set { myVar = value; }
 }

tym sposobem z chociaż podstawową walidacja w setterze bo tak jak u ciebie, to niewiele się różni od publicznego pola. 

Podobne pytania

0 głosów
0 odpowiedzi 84 wizyt
pytanie zadane 3 czerwca 2019 w C# przez DrajzleR Obywatel (1,380 p.)
0 głosów
0 odpowiedzi 100 wizyt
pytanie zadane 3 czerwca 2019 w C# przez MalwinaJ Nowicjusz (120 p.)
0 głosów
1 odpowiedź 531 wizyt
pytanie zadane 19 maja 2019 w C# przez DrajzleR Obywatel (1,380 p.)

92,584 zapytań

141,433 odpowiedzi

319,668 komentarzy

61,966 pasjonatów

Motyw:

Akcja Pajacyk

Pajacyk od wielu lat dożywia dzieci. Pomóż klikając w zielony brzuszek na stronie. Dziękujemy! ♡

Oto polecana książka warta uwagi.
Pełną listę książek znajdziesz tutaj.

Akademia Sekuraka

Kolejna edycja największej imprezy hakerskiej w Polsce, czyli Mega Sekurak Hacking Party odbędzie się już 20 maja 2024r. Z tej okazji mamy dla Was kod: pasjamshp - jeżeli wpiszecie go w koszyku, to wówczas otrzymacie 40% zniżki na bilet w wersji standard!

Więcej informacji na temat imprezy znajdziecie tutaj. Dziękujemy ekipie Sekuraka za taką fajną zniżkę dla wszystkich Pasjonatów!

Akademia Sekuraka

Niedawno wystartował dodruk tej świetnej, rozchwytywanej książki (około 940 stron). Mamy dla Was kod: pasja (wpiszcie go w koszyku), dzięki któremu otrzymujemy 10% zniżki - dziękujemy zaprzyjaźnionej ekipie Sekuraka za taki bonus dla Pasjonatów! Książka to pierwszy tom z serii o ITsec, który łagodnie wprowadzi w świat bezpieczeństwa IT każdą osobę - warto, polecamy!

...