Select object and edit on form - c#

I have a class an some objects from class. Now I want to select one of this object and display on my form. At the same time I want to edit the selected one. I used INotifyPropertyChanged and able to display selected object. Bu I have some troubles.
1- When I use myDislayingObject = myObject1 It does not work. So I have to use
myDislayingObject.property1 = myObject1.property1
myDislayingObject.property2 = myObject1.property2
I want to copy my object with all properties with one equality including events etc.
2- I am displaying properties on textboxes. When I edit the textboxes I does not changes the source object.
namespace DisplayObjectsInForm
{
public partial class Form1 : Form
{
public Araba Araba1 = new Araba();
public Araba Araba2 = new Araba();
public Araba Araba3 = new Araba();
public Araba DisplayingAraba = new Araba();
public Form1()
{
InitializeComponent();
Araba1.sName = "Araba1";
Araba1.sColor = "Kirmizi";
Araba1.nModel = 1999;
Araba2.sName = "Araba2";
Araba2.sColor = "Mavi";
Araba2.nModel = 2005;
Araba3.sName = "Araba3";
Araba3.sColor = "Gri";
Araba3.nModel = 2018;
textBox1.DataBindings.Add("Text", DisplayingAraba, "sName");
textBox2.DataBindings.Add("Text", DisplayingAraba, "sColor");
textBox3.DataBindings.Add("Text", DisplayingAraba, "nModel");
}
public class Araba : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
public string sNameInternal;
public string sName
{
get
{
return sNameInternal;
}
set
{
if (sNameInternal != value)
{
sNameInternal = value;
NotifyPropertyChanged("sName");
}
}
}
public string sColorInternal;
public string sColor
{
get
{
return sColorInternal;
}
set
{
if (sColorInternal != value)
{
sColorInternal = value;
NotifyPropertyChanged("sColor");
}
}
}
public int nModelInternal;
public int nModel
{
get
{
return nModelInternal;
}
set
{
if (nModelInternal != value)
{
nModelInternal = value;
NotifyPropertyChanged("nModel");
}
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
switch(comboBox1.SelectedIndex)
{
case 0:
{
DisplayingAraba.sName = Araba1.sName;
DisplayingAraba.sColor = Araba1.sColor;
DisplayingAraba.nModel = Araba1.nModel;
break;
}
case 1:
{
DisplayingAraba.sName = Araba2.sName;
DisplayingAraba.sColor = Araba2.sColor;
DisplayingAraba.nModel = Araba2.nModel;
break;
}
case 2:
{
//Not working
DisplayingAraba = Araba3;
break;
}
}
}
}
}

It won't work because you initially set DisplayAraba to a newAraba.Try the following
namespace DisplayObjectsInForm
{
public partial class Form1 : Form
{
public Araba Araba1 = new Araba();
public Araba Araba2 = new Araba();
public Araba Araba3 = new Araba();
public Araba DisplayingAraba;//Remove the initialization from here.
public Form1()
{
InitializeComponent();
DisplayingAraba = new Araba(); //Add this line here
Araba1.sName = "Araba1";
Araba1.sColor = "Kirmizi";
Araba1.nModel = 1999;
Araba2.sName = "Araba2";
Araba2.sColor = "Mavi";
Araba2.nModel = 2005;
Araba3.sName = "Araba3";
Araba3.sColor = "Gri";
Araba3.nModel = 2018;

Related

Update context from object function

In my window, I need to set a list of FileWatcher, for a list on machines.
For this I set a new class MachineWatcher :
public class MachineWatcher : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propName)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
private bool NotifyPropertyChanged<T>(ref T variable, T valeur, [CallerMemberName] string nomPropriete = null)
{
if (object.Equals(variable, valeur)) return false;
variable = valeur;
NotifyPropertyChanged(nomPropriete);
return true;
}
private Machine machine { get; set; }
public Machine Machine { get { return this.machine; } set { this.machine = value; } }
private string typeWatcher { get; set; } = "";
public string TypeWatcher { get { return this.typeWatcher; } set { this.typeWatcher = value; } }
FileSystemWatcher watcher { get; set; }
public FileSystemWatcher Watcher { get { return this.watcher; } set { this.watcher = value; } }
private string lastFileName { get; set; } = "";
private DateTime lastEvent { get; set; } = DateTime.MinValue;
private ObservableCollection<string> listErrors { get; set; } = new ObservableCollection<string>();
public ObservableCollection<string> ListErrors { get { return this.listErrors; } set { this.listErrors = value; NotifyPropertyChanged("ListErrors"); } }
public MachineWatcher()
{
}
public MachineWatcher(string type,string directoryStock,string fileFilter)
{
this.typeWatcher = type;
this.watcher = new FileSystemWatcher
{
Path = Path.GetDirectoryName(directoryStock),
Filter = fileFilter
};
if (this.typeWatcher=="stock")
{
this.watcher.Created += new FileSystemEventHandler(OnStockFileCreated);
}
else if(this.typeWatcher=="machine")
{
//this.watcher.NotifyFilter = NotifyFilters.Size | NotifyFilters.LastWrite | NotifyFilters.LastAccess | NotifyFilters.CreationTime;
this.watcher.Changed += OnFeedBackNesterCreated;
this.watcher.Created += OnFeedBackNesterCreated;
this.watcher.Renamed += OnFeedBackNesterCreated;
this.watcher.Deleted += OnFeedBackNesterCreated;
}
this.watcher.EnableRaisingEvents = true;
}
private void OnFeedBackNesterCreated(object source, FileSystemEventArgs e)
{
try
{
//try to read file
}
catch
{
string errorText = "Error reading file " + e.FullPath;
this.ListErrors.Add(errorText);
}
}
}
Then in my mainWindow I defined a List<MachineWatcher>
I create then like that :
MachineWatcher machineWatcher = new MachineWatcher("stock", directoryStock, "*.csv");
this.listMachineWatchers.Add(machineWatcher);
What I would like, is when my MachineWatcher meets an error, and go in catch, update a Observable<string> ListErrors, where are written all the errors for all machines.
Is there a way to call a function in MainWindows from the object MachineWatcher?
Is there a way to call a function in MainWindows from the object MachineWatcher?
Yes, assuming you have a reference to the MainWindow in MachineWatcher.
You could for example inject the MachineWatcher class with a reference to MainWindow when you instantiate it:
private readonly MainWindow mainWindow;
public MachineWatcher(string type,string directoryStock,string fileFilter, MainWindow mainWindow)
{
this.typeWatcher = type;
this.watcher ...
this.mainWindow = mainWindow;
}
MainWindow:
MachineWatcher machineWatcher = new MachineWatcher("stock", directoryStock, "*.csv", this);
Then you can call any member of mainWindow directly from the MachineWatcher class.

Unable to call method's objects into the Form

As you can see I instantiated the classes I need into the form_load, in order to use methods and classes features. The problem is that I need to Call the item NuovoCliente from CreateClientemethod, but I don't know how to do, since intellisense, even when I try to type, does not show any link to NuovoCliente.
The class you can see with the method is ClienteModel.
Which is basically structured like this:
public class ClienteModel
{
public int IDCliente { get; set; }
public string Cognome { get; set; }
public string Nome { get; set; }
public string Indirizzo { get; set; }
}
This is my method, which is placed in DBMemoryManager class:
public class DBMemoryManager : DBManager
{
//Array
ClienteModel[] MemoryClienti = new ClienteModel[0];
public int CreateCliente(ClienteModel model)
{
ClienteModel NuovoCliente = new ClienteModel();
int MaxCID = MemoryClienti.Select(ClienteModel => ClienteModel.IDCliente).Max();
MemoryClienti[0] = NuovoCliente;
NuovoCliente.IDCliente = MaxCID++;
return NuovoCliente.IDCliente;
}
This is how my Form start:
public partial class Form1 : Form
{
DBMemoryManager dbMemoryManager = null;
ClienteModel clienteModel = null;
OrdineModel ordineModel = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dbMemoryManager = new DBMemoryManager();
clienteModel = new ClienteModel();
ordineModel = new OrdineModel();
}
Return a ClienteModel from this method.
public ClienteModel CreateCliente(ClienteModel model)
{
ClienteModel NuovoCliente = new ClienteModel();
int MaxCID = MemoryClienti.Select(ClienteModel => ClienteModel.IDCliente).Max();
MemoryClienti[0] = NuovoCliente;
NuovoCliente.IDCliente = MaxCID++;
return NuovoCliente;
}
Now access data from Form_load
public partial class Form1 : Form
{
ClienteModel clienteModel = null;
OrdineModel ordineModel = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
clienteModel = new ClienteModel();
ordineModel = new OrdineModel();
DBMemoryManager dbMemoryManager = new DBMemoryManager(); //initialize here
ClienteModel nuovoCliente = dbMemoryManager.CreateCliente(clienteModel)
//here you can get all data from nuovoCliente
}
here is the data.

mvvm selected listview items to list<string> in object

I have a MVVM program with a model:
public class Deelnemer
{
public int Id { get; set; }
public string Voornaam { get; set; }
public string Werkplek { get; set; }
public List<string> Aanwezig { get; set; }
public Deelnemer()
{
}
}
In my View I have a listBox in which I want to be able to select multiple values (days to put in the list aanwezig).
<ListBox Name="listDagdelen" SelectionMode="Multiple" ItemsSource="{Binding Dagdelen}" SelectedItem="{Binding SelectedDagdeel, Mode=TwoWay}">
The ViewModel looks as follows:
class DeelnemerViewModel : INotifyPropertyChanged
{
#region Private Variables
private readonly Deelnemer dlnObject;
private readonly ObservableCollection<Deelnemer> deelnemers;
private readonly DeelnemerManager deelnemerManager;
private readonly ICommand addDeelnemerCmd;
private readonly ICommand deleteDeelnemerCmd;
#endregion
public ObservableCollection<string> Dagdelen { get; private set; }
#region constructor
public DeelnemerViewModel()
{
Dagdelen = new ObservableCollection<string>() { "maandagochtend", "maandagmiddag", "dinsdagochtend", "dinsdagmiddag", "woensdagochtend", "woensdagmiddag", "donderdagochtend", "donderdagmiddag", "vrijdagochtend", "vrijdagmiddag" };
dlnObject = new Deelnemer();
deelnemerManager = new DeelnemerManager();
deelnemers = new ObservableCollection<Deelnemer>();
addDeelnemerCmd = new RelayCommand(Add, CanAdd);
deleteDeelnemerCmd = new RelayCommand(Delete, CanDelete);
}
#endregion
#region Properties
private string _selectedDagdeel = null;
public string SelectedDagdeel
{
get { return _selectedDagdeel; }
set
{
_selectedDagdeel = value;
dlnObject.Aanwezig.Add(value);
OnPropertyChanged("SelectedDagdeel");
}
}
public int Id
{
get { return dlnObject.Id; }
set
{
dlnObject.Id = value;
OnPropertyChanged("Id");
}
}
public string Voornaam
{
get { return dlnObject.Voornaam; }
set
{
dlnObject.Voornaam = value;
OnPropertyChanged("Voornaam");
}
}
public string Werkplek
{
get { return dlnObject.Werkplek; }
set
{
dlnObject.Werkplek = value;
OnPropertyChanged("Werkplek");
}
}
public List<string> Aanwezig
{
get { return dlnObject.Aanwezig; }
set
{
dlnObject.Aanwezig = value;
OnPropertyChanged("Aanwezig");
}
}
public ObservableCollection<Deelnemer> Deelnemers { get { return deelnemers; } }
public Deelnemer SelectedDeelnemer
{
set
{
Id = value.Id;
Voornaam = value.Voornaam;
Werkplek = value.Werkplek;
Aanwezig = value.Aanwezig;
}
}
#endregion
#region Commands
public ICommand AddDeelnemerCmd { get { return addDeelnemerCmd; } }
public ICommand DeleteDeelnemerCmd { get { return deleteDeelnemerCmd; } }
#endregion
public bool CanAdd(object obj)
{
//Enable the Button only if the mandatory fields are filled
if (Voornaam != string.Empty && Werkplek != string.Empty)
return true;
return false;
}
public void Add(object obj)
{
var deelnemer = new Deelnemer { Voornaam = Voornaam, Werkplek = Werkplek, Aanwezig = Aanwezig };
if (deelnemerManager.Add(deelnemer))
{
Deelnemers.Add(deelnemer);
//string txt = string.Join(String.Empty,Aanwezig);
//MessageBox.Show(txt);
//ResetDeelnemer();
}
else
MessageBox.Show("Vul correcte waardes in!");
}
#region DeleteCommand
private bool CanDelete(object obj)
{
//Enable the Button only if the patients exist
if (Deelnemers.Count > 0)
return true;
return false;
}
private void Delete(object obj)
{
//Delete patient will be successfull only if the patient with this ID exists.
if (!deelnemerManager.Remove(Id))
MessageBox.Show("Deelnemer met dit id bestaat niet!");
else
{
//Remove the patient from our collection as well.
deelnemers.RemoveAt(GetIndex(Id));
ResetDeelnemer();
MessageBox.Show("Deelnemer succesvol verwijderd !");
}
}
#endregion
#region Private Methods
private void ResetDeelnemer()
{
Id = 0;
Voornaam = string.Empty;
Werkplek = string.Empty;
Aanwezig.Clear();
}
private int GetIndex(int Id)
{
for (int i = 0; i < Deelnemers.Count; i++)
if (Deelnemers[i].Id == Id)
return i;
return -1;
}
#endregion
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
I can't figure out how I should use the List with the listbox values. How do I add (multiple) listbox values to the object's List?
The current code throws a nullreferenceexception at
dlnObject.Aanwezig.Add(value);
You must initialize the Aanwezig property of the Deelnemer object before you can add any values to it, either in the contructor of DeelnemerViewModel:
dlnObject = new Deelnemer();
dlnObject.Aanwezig = new List<string();
...or in the constructor of the Deeelnemer class:
public Deelnemer()
{
Aanwezig = new List<string();
}

Reordering DatagridViews Columns and Saving the new Position Programmatically

I have a datagridview in my Windows form.I need to allow the users to reorder the columns and then save the changes permanantly.I set
myGrid.AllowUserToOrderColumns = true;
But this only changes the display index on design only.
Maybe an old question but I figured out something I would consider simpler.
First, at the begining of your form class, add the following fields :
public partial class MyForm : Form
{
//So whenever you change the filename, you write it once,
//everyone will be updated
private const string ColumnOrderFileName = "ColumnOrder.bin";
//To prevent saving the data when we don't want to
private bool refreshing = false;
... // the rest of your class
Then, attach to the event ColumnDisplayIndexChanged with the following mehtod :
private void MyDataGridView_ColumnDisplayIndexChanged(object sender, DataGridViewColumnEventArgs e)
{
//Because when creating the DataGridView,
//this event will be raised many times and we don't want to save that
if (refreshing)
return;
//We make a dictionary to save each column order along with its name
Dictionary<string, int> order = new Dictionary<string, int>();
foreach (DataGridViewColumn c in dgvInterros.Columns)
{
order.Add(c.Name, c.DisplayIndex);
}
//Then we save this dictionary
//Note that you can do whatever you want with it...
using (FileStream fs = new FileStream(ColumnOrderFileName, FileMode.Create))
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, order);
}
}
Then comes the OrderColumns method :
private void OrderColumns()
{
//Will happen the first time you launch the application,
// or whenever the file is deleted.
if (!File.Exists(ColumnOrderFileName))
return;
using (FileStream fs = new FileStream(ColumnOrderFileName, FileMode.Open))
{
IFormatter formatter = new BinaryFormatter();
Dictionary<string, int> order = (Dictionary<string, int>)formatter.Deserialize(fs);
//Now that the file is open, we run through columns and reorder them
foreach (DataGridViewColumn c in MyDataGridView.Columns)
{
//If columns were added between two versions, we don't bother with it
if (order.ContainsKey(c.Name))
{
c.DisplayIndex = order[c.Name];
}
}
}
}
And finally, when you fill your DataGridView :
private void FillDataGridView()
{
refreshing = true; //To prevent data saving while generating the columns
... //Fill you DataGridView here
OrderColumns(); //Reorder the column from the file
refreshing = false; //Then enable data saving when user will change the order
}
Entity:
public class Customer : INotifyPropertyChanged
{
string _firstname = "";
public string Firstname
{
get { return _firstname; }
set { _firstname = value; OnPropertyChanged("Firstname"); }
}
string _lastname = "";
public string Lastname
{
get { return _lastname; }
set { _lastname = value; OnPropertyChanged("Lastname"); }
}
int _age = 0;
public int Age
{
get { return _age; }
set { _age = value; OnPropertyChanged("Age"); }
}
public Customer()
{
}
protected void OnPropertyChanged(string name)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));
}
public event PropertyChangedEventHandler PropertyChanged;
}
The serializable Proxy:
[Serializable]
public class DataGridViewColumnProxy
{
string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
int _index;
public int Index
{
get { return _index; }
set { _index = value; }
}
public DataGridViewColumnProxy(DataGridViewColumn column)
{
this._name = column.DataPropertyName;
this._index = column.DisplayIndex;
}
public DataGridViewColumnProxy()
{
}
}
[Serializable]
public class DataGridViewColumnCollectionProxy
{
List<DataGridViewColumnProxy> _columns = new List<DataGridViewColumnProxy>();
public List<DataGridViewColumnProxy> Columns
{
get { return _columns; }
set { _columns = value; }
}
public DataGridViewColumnCollectionProxy(DataGridViewColumnCollection columnCollection)
{
foreach (var col in columnCollection)
{
if (col is DataGridViewColumn)
_columns.Add(new DataGridViewColumnProxy((DataGridViewColumn)col));
}
}
public DataGridViewColumnCollectionProxy()
{
}
public void SetColumnOrder(DataGridViewColumnCollection columnCollection)
{
foreach (var col in columnCollection)
if (col is DataGridViewColumn)
{
DataGridViewColumn column = (DataGridViewColumn)col;
DataGridViewColumnProxy proxy = this._columns.FirstOrDefault(p => p.Name == column.DataPropertyName);
if (proxy != null)
column.DisplayIndex = proxy.Index;
}
}
}
My Form1 for testing:
public partial class Form1 : Form
{
BindingSource _customers = GetCustomerList();
public BindingSource Customers
{
get { return _customers; }
set { _customers = value; }
}
public Form1()
{
InitializeComponent();
dataGridView1.DataSource = Customers;
LoadDataGridOrderFromFile("myDataGrid.xml", dataGridView1.Columns);
}
private static BindingSource GetCustomerList()
{
BindingSource customers = new BindingSource();
customers.Add(new Customer() { Firstname = "John", Lastname = "Doe", Age = 28 });
customers.Add(new Customer() { Firstname = "Joanne", Lastname = "Doe", Age = 25 });
return customers;
}
static object fileAccessLock = new object();
private static void SaveDataGridOrderToFile(string path, DataGridViewColumnCollection colCollection)
{
lock (fileAccessLock)
using (FileStream fs = new FileStream(path, FileMode.Create))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataGridViewColumnCollectionProxy));
xmlSerializer.Serialize(fs, new DataGridViewColumnCollectionProxy(colCollection));
}
}
private static void LoadDataGridOrderFromFile(string path, DataGridViewColumnCollection colCollection)
{
if (File.Exists(path))
{
lock (fileAccessLock)
using (FileStream fs = new FileStream(path, FileMode.Open))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataGridViewColumnCollectionProxy));
DataGridViewColumnCollectionProxy proxy = (DataGridViewColumnCollectionProxy)xmlSerializer.Deserialize(fs);
proxy.SetColumnOrder(colCollection);
}
}
}
private void dataGridView1_ColumnDisplayIndexChanged(object sender, DataGridViewColumnEventArgs e)
{
SaveDataGridOrderToFile("myDataGrid.xml", dataGridView1.Columns);
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.ColumnDisplayIndexChanged +=dataGridView1_ColumnDisplayIndexChanged;
}
}
It will save the DataPropertyName and the DisplayIndex into a xml file. You can extend / modify it easily where your data have to be stored by implementing your custom save and load methods.
This May Help you
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
m_Grid.AllowUserToOrderColumns = true;
SetDisplayOrder();
}
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
CacheDisplayOrder();
}
private void CacheDisplayOrder()
{
IsolatedStorageFile isoFile =
IsolatedStorageFile.GetUserStoreForAssembly();
using (IsolatedStorageFileStream isoStream = new
IsolatedStorageFileStream("DisplayCache", FileMode.Create,
isoFile))
{
int[] displayIndices =new int[m_Grid.ColumnCount];
for (int i = 0; i < m_Grid.ColumnCount; i++)
{
displayIndices[i] = m_Grid.Columns[i].DisplayIndex;
}
XmlSerializer ser = new XmlSerializer(typeof(int[]));
ser.Serialize(isoStream,displayIndices);
}
}
private void SetDisplayOrder()
{
IsolatedStorageFile isoFile =
IsolatedStorageFile.GetUserStoreForAssembly();
string[] fileNames = isoFile.GetFileNames("*");
bool found = false;
foreach (string fileName in fileNames)
{
if (fileName == "DisplayCache")
found = true;
}
if (!found)
return;
using (IsolatedStorageFileStream isoStream = new
IsolatedStorageFileStream("DisplayCache", FileMode.Open,
isoFile))
{
try
{
XmlSerializer ser = new XmlSerializer(typeof(int[]));
int[] displayIndicies =
(int[])ser.Deserialize(isoStream);
for (int i = 0; i < displayIndicies.Length; i++)
{
m_Grid.Columns[i].DisplayIndex = displayIndicies[i];
}
}
catch { }
}
}
}

How generate Graphs using modern UI Charts according to user inputs

I'm developing a program which involves graphical chart generation according to user inputs. Data for those graphs should be retrieved from the data base according to the inputs given by the user. I'm using modern UI charts library to generate charts. You can find the library here http://modernuicharts.codeplex.com/
Here is my mainWindow.xaml's screen shot :
http://imgur.com/eQUBl9w
Here user selects the graph type and pattern that he wants and the desired graph should be generated accordingly with the data available in the database. Currently I have followed the modern ui charts tutorial on above link and able to generate chart for only one LINQ query which is not based on user inputs. How can I get user inputs at runtime and execute different queries based on them and bind data at run time.
here is my mainWindo.xaml.cs
public partial class MainWindow : UserControl
{
public MainWindow()
{
InitializeComponent();
DataContext = new ChartController();
}
}
ChartController.CS
public class ChartController : INotifyPropertyChanged
{
public ObservableCollection<string> ChartTypes { get; set; }
public ChartController()
{
ChartTypes = new ObservableCollection<string>();
ChartTypes.Add("Pie");
ChartTypes.Add("Doughnut");
ChartTypes.Add("Clustered Bar");
ChartTypes.Add("Clustered Column");
ChartTypes.Add("Stacked Bar");
ChartTypes.Add("Stacked Column");
ChartTypes.Add("Stacked Bar Percentage");
ChartTypes.Add("Stacked Column Percentage");
}
private string _simpleStringProperty;
public string SimpleStringProperty
{
get { return _simpleStringProperty; }
set
{
_simpleStringProperty = value;
if (value.Equals("Pie"))
{
SelectedPageChart = new Uri("..\\Graphs\\GraphTemplates\\PieChart.xaml", UriKind.Relative);
}
if (value.Equals("Doughnut"))
{
SelectedPageChart = new Uri("..\\Graphs\\GraphTemplates\\DoughnutChart.xaml", UriKind.Relative);
}
if (value.Equals("Clustered Column"))
{
SelectedPageChart = new Uri("..\\Graphs\\GraphTemplates\\ClusteredColumnChart.xaml", UriKind.Relative);
}
if (value.Equals("Clustered Bar"))
{
SelectedPageChart = new Uri("..\\Graphs\\GraphTemplates\\ClusteredBarChart.xaml", UriKind.Relative);
}
if (value.Equals("Stacked Bar"))
{
SelectedPageChart = new Uri("..\\Graphs\\GraphTemplates\\StackedBarChart.xaml", UriKind.Relative);
}
if (value.Equals("Stacked Column"))
{
SelectedPageChart = new Uri("..\\Graphs\\GraphTemplates\\StackedColumnChart.xaml", UriKind.Relative);
}
if (value.Equals("Stacked Bar Percentage"))
{
SelectedPageChart = new Uri("..\\Graphs\\GraphTemplates\\StackedBarChart100Percent.xaml", UriKind.Relative);
}
if (value.Equals("Stacked Column Percentage"))
{
SelectedPageChart = new Uri("..\\Graphs\\GraphTemplates\\StackedColumnChart100Percent.xaml", UriKind.Relative);
}
if (value.Equals("Radial Gauge"))
{
SelectedPageChart = new Uri("..\\Graphs\\GraphTemplates\\RadialGaugeChart.xaml", UriKind.Relative);
}
OnPropertyChanged("SimpleStringProperty");
}
}
private Uri _selectedPageChart;
public Uri SelectedPageChart
{
get { return _selectedPageChart; }
set
{
_selectedPageChart = value;
OnPropertyChanged("SelectedPageChart");
}
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
PieChart.xaml
<Grid>
<metroChart:PieChart
Style="{StaticResource MinimalChartStyle}"
ChartTitle="Minimal Pie Chart"
SelectedItem="{Binding Path=SelectedItem, Mode=TwoWay}" >
<metroChart:PieChart.Series>
<metroChart:ChartSeries
SeriesTitle="Errors"
DisplayMember="Year"
ValueMember="Cost"
ItemsSource="{Binding Path=Errors}" />
</metroChart:PieChart.Series>
</metroChart:PieChart>
</Grid>
PieChart.xaml.cs
public Page1()
{
InitializeComponent();
DataContext = new ChartViewModel();
}
chartViewModel.cs
namespace ModernUIForWPFSample.WithoutBackButton.Graphs.ViewModels
{
public class ChartViewModel
{
public ObservableCollection<stockLotsCostByYear> Errors { get; private set; }
public ChartViewModel()
{
adoraDBContext _c = new adoraDBContext();
var result = from ps in _c.PurchasingShipments
group ps by ps.date.Value.Year into grp
select new
{
Year = grp.Key,
Cost = grp.Sum(x => x.NoOfPieces * x.PricePerPiece + x.Micelleneous + x.TransportCost + x.SupplierCommission)
};
Errors = new ObservableCollection<stockLotsCostByYear>();
foreach (var d in result)
Errors.Add(new stockLotsCostByYear() { Year = d.Year, Cost = d.Cost });
}
private object selectedItem = null;
public object SelectedItem
{
get
{
return selectedItem;
}
set
{
selectedItem = value;
}
}
public class TestClass
{
public string Category { get; set; }
public int Number { get; set; }
}
public class stockLotsCostByYear
{
public int Year { get; set; }
public decimal? Cost { get; set; }
}
}
}
Not tested but should be something like that :
SelectedPageChart = new Uri("..\\Graphs\\GraphTemplates\\StackedBarChart.xaml?parameter=test", UriKind.Relative)
and in StackedBarChart cs :
protected override void OnNavigatedTo(NavigationEventArgs e)
{
string parameter = string.Empty;
if (NavigationContext.QueryString.TryGetValue("parameter", out parameter)) {
this.label.Text = parameter;
}
}

Categories

Resources