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

DataContext Błąd

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

Dobry wieczór mam mały problem z programem w Wpf który wyświetla mi taki błąd "Odwołanie do obiektu nie zostało ustawione na wystąpienie obiektu.". Całkowicie nie wiem co zrobiłem źle dlatego proszę o pomoc i ewentualne wytłumaczenie rozwiązania. Oto kod 
(strona główna po zaznaczeniu check box siatka powinno nam się pojawić dodatkowe okno które pyta o jednostkę siatki a po podaniu jej rysuje siatkę na canvie zgodnie z podaną jednostką)

<Window x:Class="WpfApp1.Windows.DrawPage"
        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:WpfApp1.Windows"
        mc:Ignorable="d"

      Title="DrawPage" Height="900" Width="1600"
      Background="Wheat">
    <ScrollViewer HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden" Height="900">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="auto"></ColumnDefinition>
                <ColumnDefinition Width="auto"></ColumnDefinition>
                <ColumnDefinition Width="auto"></ColumnDefinition>
                <ColumnDefinition Width="auto"></ColumnDefinition>
                <ColumnDefinition Width="*"></ColumnDefinition>
                <ColumnDefinition Width="*"></ColumnDefinition>
                <ColumnDefinition Width="*"></ColumnDefinition>
            </Grid.ColumnDefinitions>

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

            <Label Grid.ColumnSpan="2" Content="Rysunek" FontSize="40" VerticalAlignment="Center" HorizontalContentAlignment="Center"></Label>
            
            <Label Grid.Row="1" Grid.Column="0" FontSize="20" Content="Podaj X1:"></Label>
            <TextBox Grid.Row="1" Width="100" HorizontalAlignment="Left" Grid.Column="1" Height="50" x:Name="pointX1" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" PreviewTextInput="Validation"></TextBox>

            <Label Grid.Row="1" Grid.Column="2" FontSize="20" Content="Podaj X2:"></Label>
            <TextBox Grid.Row="1" Width="100" HorizontalAlignment="Left" Grid.Column="3" Height="50" x:Name="pointX2" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" PreviewTextInput="Validation"></TextBox>

            <Label Grid.Row="2" Grid.Column="0" FontSize="20" Content="Podaj Y1:"></Label>
            <TextBox Grid.Row="2" Width="100" HorizontalAlignment="Left" Grid.Column="1" Height="50" x:Name="pointY1" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" PreviewTextInput="Validation"></TextBox>

            <Label Grid.Row="2" Grid.Column="2" FontSize="20" Content="Podaj Y2:"></Label>
            <TextBox Grid.Row="2" Width="100" HorizontalAlignment="Left" Grid.Column="3" Height="50" x:Name="pointY2" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" PreviewTextInput="Validation"></TextBox>

            <Label Grid.Row="3" Grid.Column="0"  FontSize="20" Content="Okrąg" VerticalContentAlignment="Center"></Label>
            <CheckBox Grid.Row="3" Grid.Column="1" VerticalAlignment="Center"></CheckBox>

            <Label Grid.Row="4" Grid.Column="0"  FontSize="20" Content="Trójkąd" VerticalContentAlignment="Center"></Label>
            <CheckBox Grid.Row="4" Grid.Column="1" VerticalAlignment="Center"></CheckBox>

            <Label Content="Siatka" x:Name="siatka" Grid.Row="5" Grid.Column="0"  FontSize="20" VerticalContentAlignment="Center"></Label>
            <CheckBox x:Name="siatkaCheck" Grid.Row="5" Grid.Column="1" Checked="CheckBoxSiatka_Checked" VerticalAlignment="Center"></CheckBox>

            <Label Content="Pokaż osie:" Grid.Row="6" Grid.Column="0"  FontSize="20" VerticalContentAlignment="Center"/>
            <CheckBox x:Name="Osie" Checked="Osie_Checked" Unchecked="Osie_Unchecked" Grid.Row="6" Grid.Column="1" VerticalAlignment="Center"></CheckBox>

            <Button Content="Rysuj" Grid.Row="7" Grid.Column="0" Grid.ColumnSpan="4" Height="50" Click="DrawBtn" Margin="10"></Button>
            <Button Content="Czysc" Grid.Row="8" Grid.Column="0" Grid.ColumnSpan="4" Height="50" Click="ClearBtn" Margin="10"></Button>

            <Canvas x:Name="canvas" Background="White" 
                    Margin="20" Grid.Row="1" Grid.Column="4" 
                    Width="800" Height="600" 
                    Grid.RowSpan="11" Grid.ColumnSpan="3"/>
        </Grid>
    </ScrollViewer>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Runtime.CompilerServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
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.Shapes;
using System.Xaml.Schema;

namespace WpfApp1.Windows
{
    /// <summary>
    /// Logika interakcji dla klasy DrawPage.xaml
    /// </summary>
    /// 

    class HightValueException : Exception
    {
        public HightValueException() : base("Wartości przekraczają wielkość płótna")
        {

        }
    }

    class StringValueException : Exception
    {
        public StringValueException() : base("Wartośći X i Y nie mogą być puste")
        {

        }
    }

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

        private void DrawBtn(object sender, RoutedEventArgs e)
        {
            try
            {
                if (String.IsNullOrEmpty(pointX1.Text) || String.IsNullOrEmpty(pointY1.Text) || String.IsNullOrEmpty(pointX2.Text) || String.IsNullOrEmpty(pointY2.Text))
                {
                    throw new StringValueException();
                }

                int x1value = int.Parse(pointX1.Text);
                int y1value = int.Parse(pointY1.Text);
                int x2Value = int.Parse(pointX2.Text);
                int y2Value = int.Parse(pointY2.Text);
                var myLine = new Line();
                myLine.Stroke = System.Windows.Media.Brushes.Black;
                myLine.X1 = x1value;
                myLine.Y1 = y1value;
                myLine.X2 = x2Value;
                myLine.Y2 = y2Value;
                myLine.StrokeThickness = 2;
                canvas.Children.Add(myLine);

                if (x1value > canvas.ActualHeight || y1value > canvas.ActualWidth || x2Value > canvas.ActualWidth || y2Value > canvas.ActualWidth)
                {
                    throw new HightValueException();
                }
            }
            catch (HightValueException HValue)
            {
                MessageBox.Show(HValue.Message, "Błąd");
            }
            catch(StringValueException SValue)
            {
                MessageBox.Show(SValue.Message, "Błąd");
            }
        }

        private void Validation(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^0-9]+");
            e.Handled = regex.IsMatch(e.Text);
        }

        private void CheckBoxSiatka_Checked(object sender, RoutedEventArgs e)
        {

                var siatka = new Siatka();
                siatka.ShowDialog();
                int range=0;
                siatka.DataContext = range;

                var w = canvas.Width;
                var h = canvas.Height;

                double rangex = w / range;
                double rangey = h / range;
                Line pion = new Line();
                Line poz = new Line();

                pion.X1 = 20; pion.Y1 = 0;
                pion.X2 = w / 2; pion.Y2 = h;

                poz.X1 = 0; poz.Y1 = h / 2;
                poz.X2 = w; poz.Y2 = h / 2;

                //pionowe
                for (double i = pion.X1 = 0; i <= Math.Floor(rangex); i++)
                {
                    Line l3 = new Line();
                    l3.X1 = 0 + (range * i); l3.Y1 = 0;
                    l3.X2 = 0 + (range * i); l3.Y2 = h;
                    l3.Stroke = System.Windows.Media.Brushes.Black;
                    l3.Opacity = 0.2;
                    l3.StrokeThickness = 2;
                    canvas.Children.Add(l3);
                }

                //poziome
                for (double i = pion.Y1 = 0; i <= Math.Floor(rangey); i++)
                {
                    Line l3 = new Line();
                    l3.X1 = 0; l3.Y1 = 0 + (range * i);
                    l3.X2 = w; l3.Y2 = 0 + (range * i);
                    l3.Stroke = System.Windows.Media.Brushes.Black;
                    l3.StrokeThickness = 2;
                    l3.Opacity = 0.2;
                    canvas.Children.Add(l3);
                }
            
        }

        private void Osie_Checked(object sender, RoutedEventArgs e)
        {
            var w = canvas.Width;
            var h = canvas.Height;

            Line pion = new Line();
            Line poz = new Line();

            pion.X1 = w / 2; pion.Y1 = 0;
            pion.X2 = w / 2; pion.Y2 = h;

            poz.X1 = 0; poz.Y1 = h / 2;
            poz.X2 = w; poz.Y2 = h / 2;

            pion.Stroke = System.Windows.Media.Brushes.Black;
            pion.StrokeThickness = 2;
            canvas.Children.Add(pion);

            poz.Stroke = System.Windows.Media.Brushes.Black;
            poz.StrokeThickness = 2;
            canvas.Children.Add(poz);
            
        }

        private void functionT(object sender, RoutedEventArgs e)
        {

        }

        private void Osie_Unchecked(object sender, RoutedEventArgs e)
        {
            canvas.Children.Clear();
        }

        private void ClearBtn(object sender, RoutedEventArgs e)
        {
            Osie.IsChecked = false;
            canvas.Children.Clear();
        }
    }
}

Strona Siatki

<Window x:Class="WpfApp1.Windows.Siatka"
        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:WpfApp1.Windows"
        mc:Ignorable="d"
        Title="Siatka" Height="150" Width="300">

    <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
        <Label Content="Podaj jednostkę siatki (px):"></Label>
        <TextBox x:Name="jednostka"></TextBox>
        <Button Margin="5" Content="Ok" Click="Button_Click"></Button>
    </StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.InteropServices;
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.Shapes;

namespace WpfApp1.Windows
{
    /// <summary>
    /// Logika interakcji dla klasy Siatka.xaml
    /// </summary>
    public partial class Siatka : Window
    {
        public Siatka()
        {
            InitializeComponent();
        }

        class RangeException : Exception
        {
            public RangeException() : base("Musisz podać jednostke!")
            {

            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Class1 j = new Class1();
            j.Jednostka = Convert.ToInt32(jednostka.Text);
            ((ObservableCollection<Class1>)DataContext).Add(j);
            try
            {
                if (String.IsNullOrEmpty(jednostka.Text))
                {
                    throw new RangeException();
                }
                else
                {
                    this.Close();
                }
            }
            catch(RangeException R) 
            {
                MessageBox.Show(R.Message, "Błąd");
            }
        }
    }
}

Oraz klasa

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

namespace WpfApp1
{
    public class Class1
    {
        public int Jednostka { get; set; }
    }
}

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

komentarz 17 grudnia 2022 przez areklipno Stary wyjadacz (11,930 p.)
A nie podaje Ci, w którym miejscu jest ten błąd (plik i numer linii)? Wtedy jest dużo łatwiej namierzyć błąd.
komentarz 17 grudnia 2022 przez MisticVoid Początkujący (490 p.)

Możliwe że się trochę źle wyraziłem. Nie błąd lecz wyjątek i wygląda on tak: i nie za bardzo wiem co z tym zrobić ponieważ pierwszy raz widzę taki wyjątek. Jeśli może Pan pomóc to bardzo byłbym wdzięczny.

1 odpowiedź

0 głosów
odpowiedź 18 grudnia 2022 przez areklipno Stary wyjadacz (11,930 p.)
Wydaje mi się, że nigdzie wcześniej DataContext nie został utworzony/przypisany. Tzn. nie ma nigdzie DataContext = new ObservableCollection<Class1>() lub przypisania do wartości do DataContext = KKK (gdzie KKK to wcześniej utworzona kolekcja).

Podobne pytania

0 głosów
1 odpowiedź 118 wizyt
pytanie zadane 12 grudnia 2023 w C# przez MisticVoid Początkujący (490 p.)
0 głosów
1 odpowiedź 152 wizyt
pytanie zadane 19 kwietnia 2019 w C# przez marcinconn Obywatel (1,560 p.)
–1 głos
1 odpowiedź 168 wizyt
pytanie zadane 4 sierpnia 2016 w C# przez niezalogowany

92,555 zapytań

141,403 odpowiedzi

319,554 komentarzy

61,940 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!

...