My Array is a list of Pokemon Names read from a text file and then stored into an Array in the PokemonData class seen below
private string[] pokemonNames;
private StreamReader readNames;
public PokemonData()
{
readNames = new StreamReader(setDirectory() + #".\PokemonNames.txt");
pokemonNames = new string[256];
populateArray(pokemonNames, readNames);
}
public string[] populateArray(string[] pokemonNames, StreamReader readNames)
{
string pokemonName = readNames.ReadLine();
int i = 0;
while (pokemonName != null)
{
pokemonNames[i] = pokemonName.Trim();
pokemonName = readNames.ReadLine();
i++;
}
readNames.Close();
return pokemonNames;
}
public string[] getPokemonNames()
{
return pokemonNames;
}
What I want to do is now populate an Combobox using WPF with all the names inside the array. I have tried googling this and frequently alot of the answers have classes setup much like this:
Class ExampleClass {
Public ExampleClass() {
string PokemonName; {get; set;}
}
}
I believe there is an assignment going on here, but I am unsure. C# isn't my usual language and this is my first time creating a gui. Could someone please guide me through so I could finish this.
I have tried doing a handful of things such as the code below and Databinding. At this point I believe I am missing something.
<Window
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:StarterEdit"
xmlns:Collections="clr-namespace:System.Collections;assembly=System.Runtime.Extensions" x:Class="StarterEdit.MainWindow"
mc:Ignorable="d"
Title="Starter Edit" Height="420" Width="550">
<Grid Margin="0,0,0,11" HorizontalAlignment="Center" Width="530">
<Label Content="Squirtle" HorizontalAlignment="Left" Margin="45,50,0,0" VerticalAlignment="Top" ToolTip="Starter One"/>
<Label Content="Bulbasaur" HorizontalAlignment="Left" Margin="245,50,0,0" VerticalAlignment="Top" ToolTip="Starter Two"/>
<Label Content="Charmander" HorizontalAlignment="Left" Margin="445,50,0,0" VerticalAlignment="Top" ToolTip="Starter Three"/>
<ComboBox x:Name="NameList" HorizontalAlignment="Left" Margin="10,81,0,0" VerticalAlignment="Top" Width="120" IsReadOnly="True" SelectedIndex="0" Cursor="Arrow" IsTextSearchEnabled="True" ToolTip="List of Pokemon names">
</ComboBox>
</Window>
Here is my MainWindow class
public partial class MainWindow : Window
{
Dictionary<int, string> pokemonNames = new Dictionary<int, string>();
PokemonData pokemonData = new PokemonData();
public MainWindow()
{
InitializeComponent();
NameList.ItemsSource = pokemonData.getPokemonNames(); //method that returns string array
NameList.ItemsSource = pokemonNames; //this is a dictionary
}
}
What I'm trying to do is using WPF I want to populate my comboBox with the data from the PokemonData Class, specifically the array containing all the names. The problem is whenever I bind the data or set the data it never displays on the gui or in the comboBox.
If shortly, the next code must work correctly, just do this initialization after loading data from the file.
NameList.ItemsSource = pokemonData.getPokemonNames();
If you want a better solution, you can find it below (when Pokemons collection have changed UI would be updated automatically):
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new PokemonData(setDirectory() + #".\PokemonNames.txt");
}
}
public class Pokemon
{
public int ID { get; set; }
public string Name { get; set; }
}
public class PokemonData
{
public ObservableCollection<Pokemon> Pokemons { get; set; } = new ObservableCollection<Pokemon>();
public PokemonData(string path)
{
LoadData(path);
}
private void LoadData(string path)
{
Pokemons.Clear();
using (StreamReader stream = new StreamReader(path))
{
int i = 1;
while (true)
{
string pokemonName = stream.ReadLine();
if (pokemonName != null)
Pokemons.Add(new Pokemon { ID = i, Name = pokemonName.Trim() });
else break;
i++;
}
}
}
}
And XAML code:
<ComboBox ItemsSource="{Binding Pokemons}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Related
I am new with WPF and I am struggling a little bit, trying to display all data in a list I can see the objects there in the view(two lines) but nothing is displayed like Name ?? any recommendation ?? Thank you
xaml :
<ListBox x:Name="nadjib">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
cs :
public ExecuteSpecificJobView()
{
InitializeComponent();
List<string> ext = new List<string>();
ext.Add(".txt");
//itemsControl. = new List<string>(){ "ok","yes" };
ObservableCollection<ViewModels.CreateJobViewModel.Model.TaskJsonAttribute> jobs = new ObservableCollection<ViewModels.CreateJobViewModel.Model.TaskJsonAttribute>();
jobs.Add(new ViewModels.CreateJobViewModel.Model.TaskJsonAttribute { name = "aliii", source = "ok", target = "yess", type = "complete", extension = ext });
jobs.Add(new ViewModels.CreateJobViewModel.Model.TaskJsonAttribute { name = "aliii", source = "ok", target = "yess", type = "complete", extension = ext });
nadjib.ItemsSource = jobs;
}
public class TaskJsonAttribute
{
public string name;
public string source;
public string target;
public string type;
public List<string> extension;
public string Name
{
get { return name; }
}
}
Here is a little project that is similar to yours. This is showing the two names in the Listbox. See how this differ from yours.
XAML
<Window x:Class="WpfApp9.MainWindow"
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:WpfApp9"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<ListBox x:Name="nadjib">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
MainWindow.xaml.cs
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
namespace WpfApp9
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ObservableCollection<TaskJsonAttribute> jobs = new ObservableCollection<TaskJsonAttribute>();
jobs.Add(new TaskJsonAttribute() { name = "aliii-1" });
jobs.Add(new TaskJsonAttribute() { name = "aliii-2" });
nadjib.ItemsSource = jobs;
}
}
public class TaskJsonAttribute
{
public string name;
public string source;
public string target;
public string type;
public List<string> extension;
public string Name
{
get { return name; }
}
}
}
I'd like to access ComboBox items (which are defined in another class) in MainWindow.xaml.cs, but I can't.
I'm new to C# and WPF. The purpose of this code is to get a selected ComboBox item as a search key. I have copied from many example codes on the Internet and now I'm completely lost. I don't even know which part is wrong. So, let me show the entire codes (sorry):
MainWindow.xaml:
<Window x:Class="XY.MainWindow"
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:XY"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="454.4">
<Grid>
<DataGrid ItemsSource="{Binding channels}"
SelectedItem="{Binding SelectedRow, Mode=TwoWay}"
Margin="0,0,0,-0.2">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding name}"
Header="Channel" Width="Auto"/>
<DataGridTemplateColumn Width="100" Header="Point Setting">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox x:Name="piontsComboBox"
ItemsSource="{Binding DataContext.points,
RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
SelectionChanged="PrintText"
DisplayMemberPath="name"
SelectedValuePath="name"
Margin="5"
SelectedItem="{Binding DataContext.SelectedPoint,
RelativeSource={RelativeSource AncestorType={x:Type Window}},
Mode=TwoWay}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<TextBox x:Name="tb" Width="140" Height="30" Margin="10,250,200,30"></TextBox>
<Button x:Name="Browse_Button" Content="Browse" Margin="169,255,129.6,0"
Width="75" Click="Browse_Button_Click" Height="30" VerticalAlignment="Top"/>
</Grid>
MainWindow.xaml.cs:
using System;
using System.Windows;
using System.Windows.Controls;
namespace XY
{
public partial class MainWindow : Window
{
public GridModel gridModel { get; set; }
public MainWindow()
{
InitializeComponent();
gridModel = new GridModel();
this.DataContext = gridModel;
}
private void Browse_Button_Click(object sender, RoutedEventArgs e)
{
WakeupClass clsWakeup = new WakeupClass();
clsWakeup.BrowseFile += new EventHandler(gridModel.ExcelFileOpen);
clsWakeup.Start();
}
void PrintText(object sender, SelectionChangedEventArgs args)
{
//var item = pointsComboBox SelectedItem as Point;
//if(item != null)
//{
// tb.Text = "You selected " + item.name + ".";
//}
MessageBox.Show("I'd like to show the item.name in the TextBox.");
}
}
public class WakeupClass
{
public event EventHandler BrowseFile;
public void Start()
{
BrowseFile(this, EventArgs.Empty);
}
}
}
Point.cs:
namespace XY
{
public class Point : ViewModelBase
{
private string _name;
public string name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("name");
}
}
private int _code;
public int code
{
get { return _code; }
set
{
_code = value;
OnPropertyChanged("code");
}
}
}
}
Record.cs:
namespace XY
{
public class Record : ViewModelBase
{
private string _name;
public string name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("name");
}
}
private int _PointCode;
public int PointCode
{
get { return _PointCode; }
set
{
_PointCode = value;
OnPropertyChanged("PointCode");
}
}
private Record _selectedRow;
public Record selectedRow
{
get { return _selectedRow; }
set
{
_selectedRow = value;
OnPropertyChanged("SelectedRow");
}
}
private Point _selectedPoint;
public Point SelectedPoint
{
get { return _selectedPoint; }
set
{
_selectedPoint = value;
_selectedRow.PointCode = _selectedPoint.code;
OnPropertyChanged("SelectedRow");
}
}
}
}
ViewModelBase.cs:
using System.ComponentModel;
namespace XY
{
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
}
GridModel.cs:
using System.Collections.ObjectModel;
using System.Windows;
namespace XY
{
public class GridModel : ViewModelBase
{
public ObservableCollection<Record> channels { get; set; }
public ObservableCollection<Point> points { get; set; }
public GridModel()
{
channels = new ObservableCollection<Record>() {
new Record {name = "High"},
new Record {name = "Middle"},
new Record {name = "Low"}
};
}
internal void ExcelFileOpen(object sender, System.EventArgs e)
{
points = new ObservableCollection<Point> { new Point { } };
points.Add(new Point { name = "point1", code = 1 });
points.Add(new Point { name = "point2", code = 2 });
points.Add(new Point { name = "point3", code = 3 });
MessageBox.Show("Assume that Excel data are loaded here.");
}
}
}
The procedure goes like:
Click on the "Browse" button to load the data.
Click on the 1st column "Channel" to sort the list (This is a bug, but if you don't, the "Point Setting" items won't show up).
Click on the "Point Setting" ComboBox to select the items (point1, point2, ..., etc.).
This code is supposed to show the selected item name in the TextBox.
If everything is in MainWindow.xaml.cs, the ComboBox items could be accessed. Since I split the codes into different classes, it has not been working. Please help me. Any suggestion would be helpful.
Your binding does work. You can make use of the sender object to achieve what you wanted.
void PrintText(object sender, SelectionChangedEventArgs args)
{
var comboBox = sender as ComboBox;
var selectedPoint = comboBox.SelectedItem as Point;
tb.Text = selectedPoint.name;
}
The problem is that the DataGridColumn is not part of the WPF logical tree and so your relative source binding will not work. The only way to get your binding to work is a type of kluge (very common with WPF in my experience). Create a dummy element that is in the logical tree and then reference that.
So
<FrameworkElement x:Name="dummyElement" Visibility="Collapsed"/>
<DataGrid ItemsSource="{Binding channels}"
SelectedItem="{Binding SelectedRow, Mode=TwoWay}"
Margin="0,0,0,-0.2">
Then your binding will look like this
<ComboBox x:Name="piontsComboBox"
ItemsSource="{Binding DataContext.points,
Source={x:Reference dummyElement}}"
SelectionChanged="PrintText"
DisplayMemberPath="name"
SelectedValuePath="name"
Margin="5"
SelectedItem="{Binding DataContext.SelectedPoint,
Source={x:Reference dummyElement},
Mode=TwoWay}"/>
If I have an ObservableCollection in one of my classes. In my code behind my view I have an object of this class and use it as the DataBinding
this.DataContext = MyCustomClass;
in the xaml code of the view I want to bind several buttons to items in the Observable collection. Something like this:
<Button x:Name="Bid_Price_10" Grid.Row="0" Content="{Binding myObservableCollection[0].Price, Mode=OneWay}" Grid.ColumnSpan="2" HorizontalAlignment="Stretch" UseLayoutRounding="True" Padding="0"/>
<Button x:Name="Bid_Price_11" Grid.Row="1" Content="{Binding myObservableCollection[1].Price, Mode=OneWay}" Grid.ColumnSpan="2" HorizontalAlignment="Stretch" UseLayoutRounding="True" Padding="0"/>
At the moment this is not working, am I missing something ?
EDIT: Create full code to demo what I am trying to do:
So I have a Coffee class:
class Coffee
{
public int price { get; set; }
}
I have a drinks class that holds a list of coffees:
class Drinks
{
public List<Coffee> CoffeeList;
public Drinks()
{
CoffeeList = new List<Coffee>();
for (int i = 0; i < 10; i++)
{
Coffee c = new Coffee();
c.price = i;
CoffeeList.Add(c);
}
this.startCoffeePriceUpdateThread();
}
private void UpdateCofffeePrice()
{
while (true)
{
Thread.Sleep(1000);
foreach (var c in CoffeeList)
{
c.price++;
}
}
}
public void startCoffeePriceUpdateThread()
{
Thread coffeeThread = new Thread(new ThreadStart(UpdateCofffeePrice));
coffeeThread.Start();
}
}
my main window code behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Drinks ourDrinks = new Drinks();
this.DataContext = ourDrinks;
}
}
and my xaml code:
<Grid x:Name="Grid" HorizontalAlignment="Left" Height="193" Margin="77,31,0,0" VerticalAlignment="Top" Width="315">
<Button x:Name="Button" Content="{Binding CoffeeList[0].Price}" HorizontalAlignment="Left" Margin="49,25,0,0" VerticalAlignment="Top" Width="75" Height="28"/>
</Grid>
So the problem is that I am not seeing anything in the button. At the moment I am not using INotifyPropertyChange as I have been advised it would not be needed.
As Clemens suggested: if everything is fixed, you won't need ObservableCollection nor PropertyChanged notification. The following code should be sufficient:
public class Stuff
{
public string Price { get; set; }
}
public class myCustomClass
{
public List<Stuff> myCollection { get; set; }
}
public partial class MainWindow : Window
{
public myCustomClass myCustomInstance = new myCustomClass();
public MainWindow()
{
InitializeComponent();
myCustomInstance.myCollection = new List<Stuff>();
myCustomInstance.myCollection.Add(new Stuff() { Price = "1200$" });
myCustomInstance.myCollection.Add(new Stuff() { Price = "5.5$" });
this.DataContext = myCustomInstance;
}
}
And the simplified XAML
<Button Content="{Binding myCollection[0].Price, Mode=OneWay}"/>
<Button Content="{Binding myCollection[1].Price, Mode=OneWay}" />
NB: I specified an instance of myCustomClass as the DataContext. If you really need to bind it to the class, let me know and I will update the code.
So I have an api call that runs a query and returns a JSON response. Because of the structure of the JSON response I have created a class that I can use Json.Net to Deserialize the return straight into. Here is the example class:
public class QuerySet
{
public List<Column> Columns { get; set; }
public class Column
{
public List<string> Name { get; set; }
}
public List<RowSet> Rows { get; set; }
public class RowSet
{
public List<DataSet> Row { get; set; }
public class DataSet
{
public List<string> Data { get; set; }
}
}
}
Now, a single API call can contain several query sets, so for each return, I generate a list of query sets, that I then want to data bind a DataGrid to each set. Here is an example of what I have so far in the code behind my window:
public List<DataGrid> QueryResults;
public QueryResultsWindow(string _name, JObject _returns)
{
InitializeComponent();
QueryNameText.Text = _name;
QueryResults = new List<DataGrid>();
JArray sets = (JArray)_returns.SelectToken("$..Set");
foreach(JObject set in sets)
{
DataGrid dg = new DataGrid();
QuerySet s = new QuerySet();
s = JsonConvert.DeserializeObject<QuerySet>(set.ToString());
dg.ItemsSource = s.Rows;
QueryResults.Add(dg);
}
ResultsListBox.ItemsSource = QueryResults;
}
The issue here as you might see is that for each particular DataGrid, I want the Column Headers bound to the Name property, and the data populated from the Data properties.
Here is how I currently have the XAML setup in the window:
<DockPanel>
<StackPanel Orientation="Horizontal" DockPanel.Dock="Top" VerticalAlignment="Top">
<TextBlock x:Name="QueryNameText" Margin="5"></TextBlock>
<Button Content="Export Results" Click="Button_Click" Margin="5"></Button>
</StackPanel>
<ListBox DockPanel.Dock="Top" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="3" Name="ResultsListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<DataGrid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding UpdateSourceTrigger=PropertyChanged}" CanUserAddRows="False" IsReadOnly="True" SelectionUnit="Cell">
<DataGrid.Columns>
<DataGridTextColumn Header="{Binding Name}"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DockPanel>
I know that if I wanted to create a custom class for each possible return type, this would be much easier. However, given the hundreds of potential return types, this does not seem very feasible. I've tried using DataTables, I've tried setting the DataGrid in the ListBox in XAML, but I may not have implemented this correctly, and finally came to the resolution of trying to create a list of DataGrids and then binding to those.
I could use some help.
Thanks!
SO after some messing around with this. Here is the answer I came up with.
I took the query set class above and added a method to build a DataTable inside the QuerySet Class:
public class QuerySet
{
public DataTable BindableTable { get; private set; }
public static List<string> ColumnName { get; private set; }
public static List<RowSet.DataSet> RowsSet { get; private set; }
public List<Column> Columns { get; set; }
public class Column
{
private List<string> _name;
public List<string> Name
{
get { return _name; }
set { _name = value; ColumnName = _name; }
}
}
public List<RowSet> Rows { get; set; }
public class RowSet
{
private List<DataSet> _row;
public List<DataSet> Row
{
get { return _row; }
set { _row = value; RowsSet = _row; }
}
public class DataSet
{
public List<string> Data { get; set; }
}
}
public void GetDataGridTable()
{
DataTable table = new DataTable();
foreach(string name in ColumnName)
{
table.Columns.Add(name);
}
foreach(RowSet.DataSet set in RowsSet)
{
DataRow row = table.NewRow();
int counter = 0;
foreach(string item in set.Data)
{
row[counter] = item;
counter++;
}
table.Rows.Add(row);
}
BindableTable = table;
}
}
I added a couple of accessors to make getting to the nested bits easier, and built a DataTable from there. In my code behind my popup window, I created an Observable Collection of DataGrids, and set the DataContext of each Grid to a DataView based on the QuerySet:
public ObservableCollection<DataGrid> QueryResults;
public event PropertyChangedEventHandler PropertyChanged;
public QueryResultsWindow(string _name, JObject _returns)
{
InitializeComponent();
QueryNameText.Text = _name;
QueryResults = new ObservableCollection<DataGrid>();
JArray sets = (JArray)_returns.SelectToken("$..Set");
foreach(JObject set in sets)
{
DataGrid dg = new DataGrid();
QuerySet s = new QuerySet();
s = JsonConvert.DeserializeObject<QuerySet>(set.ToString());
s.GetDataGridTable();
DataView newView = new DataView(s.BindableTable);
dg.ItemsSource = newView;
dg.CanUserAddRows = false;
dg.CanUserDeleteRows = false;
QueryResults.Add(dg);
}
ResultsListBox.ItemsSource = QueryResults;
}
Then the XAML inside my popup window was pretty straight forward:
<DockPanel>
<StackPanel Orientation="Horizontal" DockPanel.Dock="Top" VerticalAlignment="Top">
<TextBlock x:Name="QueryNameText" Margin="5"></TextBlock>
<Button Content="Export Results" Click="Button_Click" Margin="5"></Button>
</StackPanel>
<ListBox DockPanel.Dock="Top" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="3" Name="ResultsListBox" ItemsSource="{Binding QueryResults}">
</ListBox>
</DockPanel>
Obviously this is not the most elegant solution. Even just looking at it here I could easily create the DataView in the QuerySet class rather than doing that conversion in the code behind. So, while the answer isn't perfect, it's working for now.
I have a ListBox I want to fill with data from two TextBoxesby clicking a Button. I think the problem comes from the differents textblock i have in my listbox. Here is what i want in image :
TheUI
The MainWindow.xaml of my listbox :
<ListBox x:Name="listBox"
ItemsSource="{Binding Issues}" Grid.Column="1" HorizontalAlignment="Left" Height="366" VerticalAlignment="Top" Width="453" Margin="0,0,-1,0">
<StackPanel Margin="3">
<DockPanel >
<TextBlock FontWeight="Bold" Text="Issue:"
DockPanel.Dock="Left"
Margin="5,0,10,0"/>
<TextBlock Text=" " />
<TextBlock Text="{Binding Issue}" Foreground="Green" FontWeight="Bold" />
</DockPanel>
<DockPanel >
<TextBlock FontWeight="Bold" Text="Comment:" Foreground ="DarkOrange"
DockPanel.Dock="Left"
Margin="5,0,5,0"/>
<TextBlock Text="{Binding Comment}" />
</DockPanel>
</StackPanel>
</ListBox>
My MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public sealed class ViewModel
{
public ObservableCollection<Issue> Issues { get; private set; }
public ViewModel()
{
Issues = new ObservableCollection<Issue>();
}
}
private void addIssue_Click(object sender, RoutedEventArgs e)
{
var vm = new ViewModel();
vm.Issues.Add(new Issue { Name = "Jon Skeet", Comment = "lolilol" });
DataContext = vm;
InitializeComponent();
}
}
My Issue.cs :
public sealed class Issue
{
public string Name { get; set; }
public string Comment { get; set; }
}
I follow this tutorial but i don't want to implement a Database :
Tuto
I also try to use this stackoverflow question
The error i have is 'System.InvalidOperationException' The Items collection must be empty to use ItemsSource
But not sure this is the heart of the problem.
Remove whatever you have inserted between <ListBox> and </ListBox>, as it is treated as part of Items collection.
Instead shift that content between <ListBox.ItemTemplate>...</ListBox.ItemTemplate>.
You don't need to update Context and InitializeComponent every time, atleast to your case.
public partial class MainWindow : Window
{
ViewModel vm = new ViewModel();
public MainWindow()
{
InitializeComponent();
DataContext = vm;
}
public sealed class ViewModel
{
public ObservableCollection<Issue> Issues { get; private set; }
public ViewModel()
{
Issues = new ObservableCollection<Issue>();
}
}
private void addIssue_Click(object sender, RoutedEventArgs e)
{
vm.Issues.Add(new Issue { Name = "Jon Skeet", Comment = "lolilol" });
}
}