In my wpf application, I've created two view classes, DayView and CustomView. In DayView, there is a listbox consist of some entries. In listbox, there is stackpanel with 5 textboxes. In my CustomView class, also I've created stackpanel with 5 textboxes. when I enter data into those textboxes of CustomView and click on save button,the new entry should create and data should saved in respective textboxes of DayView.
CustomView class:
namespace TimeSheet
{
/// <summary>
/// Interaction logic for CustomView.xaml
/// </summary>
public partial class CustomView : Window
{
public List<Harvest_Project> projectList { get; set; }
public List<Harvest_Client> clientList { get; set; }
public Harvest_Project selectedProjectid { get; set; }
public Harvest_Client selectedClientid { get; set; }
private string client { get { return ClientText.Text; } set { ClientText.Text=value;} }
private string application { get { return ApplicationText.Text; } set { ApplicationText.Text = value; } }
private string starttime { get { return StartTimeText.Text; } set { StartTimeText.Text = value; } }
private string stoptime { get { return StopTimeText.Text; } set { StopTimeText.Text = value; } }
private string task { get { return TaskText.Text; } set { TaskText.Text = value; } }
private string project { get { return ProjectText.Text; } set { ProjectText.Text = value; } }
public CustomView()
{
InitializeComponent();
this.DataContext = this;
Globals._globalController.setCustomViewWindow(this);
clientList = Globals._globalController.harvestManager._CLIENTLIST;
projectList = Globals._globalController.harvestManager._PROJECTLIST;
}
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
if (sender is Harvest_TimeSheetEntry)
{
//Harvest_TimeSheetEntry entry = new Harvest_TimeSheetEntry();
//if (!entry.isSynced)
//{
// entry.ClientNameBinding = client;
// entry.ApplicationNameBinding = application;
// entry.StartTimeBinding = starttime;
// entry.StopTimeBinding = stoptime;
// entry.TaskNameBinding = task;
// entry.ProjectNameBinding = project;
//}
Globals._globalController.getDayViewWindow.Show();
this.Hide();
}
}
private void ClientComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string text = (sender as ComboBox).SelectedItem.ToString();
}
private void ProjectComboBoxChanged(object sender, SelectionChangedEventArgs e)
{
string text = (sender as ComboBox).SelectedItem.ToString();
}
}
}
I don't understand, how should i save this data in DayView listbox. Please suggest some ways.!
This is DayView window
[1]: http://i.stack.imgur.com/1Qi0e.png
This is CustomView window!
[2]: http://i.stack.imgur.com/mACxR.png
In my opinion it's more suitable to use an mvvm Framework to make your solution more structured, and then use a Messenger to make communication between your views.
Related
I want to create a C# Windows Form application where there is a flow layout panel, filled with User Control elements. Every time I click an element, the some labels must show its attributes. However, the click event doesn't register. I added some breakpoints on the show_preview() method and it never calls the method. The Load event is calling show_preview but I want to do change the labels acordinging to a User Control being clicked.
This is the Form:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
load_plots();
}
private void load_plots()
{
ArrayList items = new ArrayList();
for (int i = 0;i<100;i++)
{
PlotItem plot = new PlotItem();
plot.Place = "Ilion";
plot.Price = i * 1000;
plot.Space = i * 10;
plot.Title = "Plot No." + i;
plot.Width = flowLayoutPanel1.Width - 30;
plot.Click += new EventHandler(this.show_preview);
items.Add(plot);
flowLayoutPanel1.Controls.Add(plot);
}
}
private void show_preview(object sender, EventArgs e)
{
PlotItem clicked = sender as PlotItem;
plot_title.Text = "Hello";
plot_size.Text = clicked.Space.ToString();
plot_value.Text = clicked.Price.ToString();
}
This is the Plot Item:
public partial class PlotItem : UserControl
{
public PlotItem()
{
InitializeComponent();
}
#region Properties
[Category("Plot Object")]
private String _place;
public String Place
{
get { return _place; }
set { _place = value; }
}
[Category("Plot Object")]
private double _price;
public double Price
{
get { return _price; }
set { _price = value; label_price.Text = value.ToString() + "€"; }
}
[Category("Plot Object")]
private String _use;
public String Use
{
get { return _use; }
set { _use = value; }
}
[Category("Plot Object")]
private double _space;
public double Space
{
get { return _space; }
set { _space = value; label_size.Text = value.ToString() + "m2"; }
}
[Category("Plot Object")]
private String _title;
public String Title
{
get { return _title; }
set { _title = value; label_title.Text = value; }
}
[Category("Plot Object")]
private Image _icon;
public Image Icon
{
get { return _icon; }
set { _icon = value; plot_preview.Image = value; }
}
#endregion
private void panel1_MouseEnter(object sender, EventArgs e)
{
this.BackColor = Color.Silver;
}
private void panel1_MouseLeave(object sender, EventArgs e)
{
this.BackColor = System.Drawing.SystemColors.Control;
}
Thanks for your time.
I want to access labelNummer.Text from my User Control in my form.
Form
if (idPartijen.Contains(labelNummer.Text))
{
con.SqlQuery("SELECT * FROM `kandidaat` where `partijnummer` =#nummer ");
con.Cmd.Parameters.Add("#nummer", MySql.Data.MySqlClient.MySqlDbType.VarString).Value = labelNummer.Text;
User Control
public string KandidaatNummer
{
set
{
Nummer = value;
labelNummer.Text = Nummer;
}
}
Your UserControl
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
}
private void MyUserControl_Load(object sender, EventArgs e)
{
}
public string KandidaatNummer
{
get
{
return labelNummer.Text;
}
set
{
labelNummer.Text = value;
}
}
}
Let's say that your user control has a name called: MyUserControl1
if (idPartijen.Contains(myUserControl1.KandidaatNummer)) { ... }
I am working on a C# project which includes WPF. I was wondering, If I could somehow check If my data grid contains certain element.
For example,
I have combo box whose itemsSource is some list of objects. Now, when an user selects an item from the combo box and presses the button
below in data grid (in same window) that item shows up.
I want to forbid the user to select same item more than once and for example put MessageBox with error message. How could I do that?
Code
This Window:
public partial class AvioWindowAddNEdit : Window
{
Avio avio;
public enum Stage { ADD, EDIT};
Stage stage;
public AvioWindowAddNEdit(Avio avio, Stage stage = Stage.ADD)
{
InitializeComponent();
this.avio= avio;
this.stage= stage;
textboxCode.DataContext = avio;
comboboxListofFlights.ItemsSource = Aplikacija.Instance.Flights;
comboboxListofFlights.DataContext = avio;
datagridListofFlights.ItemsSource = avio.ListofFlights;
datagridListofFlights.ColumnWidth = new DataGridLength(1, DataGridLengthUnitType.Auto);
if (stage== Stage.EDIT)
{
textboxCode.IsEnabled = false;
}
}
}
Button which adds selected item to data grid:
private void btnAddFlight_Click(object sender, RoutedEventArgs e)
{
avio.ListOfFlights.Add(comboboxListOfFlights.SelectedItem as Flight);
}
Singleton class for loading in all of my data:
class Aplication
{
public ObservableCollection<User> Users { get; set; }
public ObservableCollection<Airport> Airports { get; set; }
public ObservableCollection<Flight> Flights{ get; set; }
public ObservableCollection<Avio> Avios { get; set; }
public string LoggedInUser { get; set; }
private static Aplication instance = new Aplication();
public static Aplication Instance
{
get
{
return instance;
}
}
private Aplication()
{
Users= new ObservableCollection<User>();
Airports = new ObservableCollection<Airport>();
Flights = new ObservableCollection<Flight>();
Avios= new ObservableCollection<Avio>();
FillInData(); //method where I filled in all of these ObservableCollections
}
}
My class:
public class Avio : ObservableObject, ICloneable
{
//observableobject is an object where I implemented INotifyPropertyChanged
private string code;
public string Code
{
get { return code; }
set { code= value; OnPropertyChanged("Code"); }
}
private ObservableCollection<Flight> listOfFlights;
public ObservableCollection<Flight> ListOfFlights
{
get { return listOfFlights; }
set { listOfFlights= value; OnPropertyChanged("ListOfFlights"); }
}
private bool active;
public bool Active
{
get { return active; }
set { active= value; OnPropertyChanged("Active"); }
}
public Avio()
{
active= true;
ListOfFlights = new ObservableCollection<Flight>();
}
public Avio(string code)
{
active= true;
ListOfFlights = new ObservableCollection<Flight>();
Code= code;
}
}
You could use an ObservableCollection as an ItemsSource for your DataGrid. In that way you'll always have easy access to the data via code.
Check out this tutorial as a starting point (this uses ListBox instead of DataGrid, but it's easily adaptable to DataGrid).
I am in trouble while working on Databinding in windows form. I have two classes, one is Project and another is Update. Now all project object is having a list of Updates and it is binded to a combobox, but when the user changes selection need to display/bind the properties of Update object to another controls. But is not updating as expected, when the user changes selection. Please help me on this..
Screenshot
See my class and codes below,
public class Project
{
private int _id;
private string _name;
public Project(int id, string name)
{
_id = id;
_name = name;
ReadUpdates();
}
public List<Update> AvailableUpdates { get; set; }
public int Id { get { return _id; } }
public string ProjName
{
get { return _name; }
set { _name = value; }
}
private void ReadUpdates()
{
AvailableUpdates = new List<Update>();
for (int i = 0; i < 10; i++)
{
AvailableUpdates.Add(new
Update(i, DateTime.Now.AddDays(i)));
}
}
}
public class Update
{
private string _title;
private int _uid;
private DateTime _updatedOn;
public Update(int id, DateTime updatedOn)
{
_title = $"Update:{id}";
_uid = id;
_updatedOn = updatedOn;
}
public string Title
{
get { return _title; }
set { _title = value; }
}
public int UId
{
get { return _uid; }
set { _uid = value; }
}
public DateTime UpdatedOn
{
get { return _updatedOn; }
set { _updatedOn = value; }
}
}
public partial class Form1 : Form
{
private Update _currentUpdate;
private Project _project;
public Form1()
{
InitializeComponent();
_project = new Project(1, "Sample Project");
DoBindings();
}
private void DoBindings()
{
NameBox.DataBindings.Add("Text", _project, "ProjName");
IdBox.DataBindings.Add("Text", _project, "Id");
UpdatesCombo.DataSource = _project.AvailableUpdates;
UpdatesCombo.DisplayMember = "UId";
_currentUpdate = (Update)UpdatesCombo.SelectedItem;
UpdateTitle.DataBindings.Add("Text", _currentUpdate, "Title");
UpdateDate.DataBindings.Add("Value", _currentUpdate, "UpdatedOn");
}
private void UpdatesCombo_SelectionChangeCommitted(object sender, System.EventArgs e)
{
_currentUpdate = (Update)UpdatesCombo.SelectedItem;
}
}
Please correct me if I am wrong.
It's quite simple. All you need is to bind the related controls to the same list data source as the combo box.
var updates = _project.AvailableUpdates;
UpdatesCombo.DataSource = updates;
UpdatesCombo.DisplayMember = "UId";
UpdateTitle.DataBindings.Add("Text", updates, "Title");
UpdateDate.DataBindings.Add("Value", updates, "UpdatedOn");
The data binging infrastructure creates CurrencyManager class per each unique list data source. The non list controls are actually bound to the Current property, which is updated by the combo box selection.
I have simple app, where ObservableCollection is updating in code and when new item added the UI is updated too. To update UI i am using a Dispatcher which is passed as a property to ViewModel. My code is works, but i don't know right i am or not.
Here is the code:
MainWindow.xaml.cs
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
MainWindowViewModel model = new MainWindowViewModel();
public MainWindow()
{
InitializeComponent();
this.DataContext = model;
this.model.dispatcher = this.Dispatcher;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string url = urlToCheck.Text;
Task task = new Task(() =>
{
model.GetUrls(url);
});
task.ContinueWith((previousTask) =>
{
label.Content = "Все ссылки собраны.";
},
TaskScheduler.FromCurrentSynchronizationContext());
label.Content = "Идёт сбор ссылок...";
task.Start();
}
}
MainWindowViewModel.cs
class MainWindowViewModel
{
public ObservableCollection<Url> Urls { get; set; }
public bool NeedToGetResponseForChildUrls { get; set; }
public bool NeedToDeletePreviousResults { get; set; }
public Dispatcher dispatcher;
some code.....................
**and something like this i am updating ObservableCollection:**
if (NeedToDeletePreviousResults)
{
dispatcher.Invoke(() =>
{
Urls.Clear();
});
}
Url.cs
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace CheckUrl
{
public class Url : INotifyPropertyChanged
{
private string _absoluteUrl;
public string AbsoluteUrl
{
get { return _absoluteUrl; }
set
{
if (_absoluteUrl != value)
{
_absoluteUrl = value;
OnPropertyChanged("AbsoluteUrl");
}
}
}
private int _responseStatusCode;
public int ResponseStatusCode
{
get { return _responseStatusCode; }
set
{
if (_responseStatusCode != value)
{
_responseStatusCode = value;
OnPropertyChanged("ResponseStatusCode");
}
}
}
private string _responseStatusDescription;
public string ResponseStatusDescription
{
get { return _responseStatusDescription; }
set
{
if (_responseStatusDescription != value)
{
_responseStatusDescription = value;
OnPropertyChanged("ResponseStatusDescription");
}
}
}
public enum Status { Working, Broken };
private Status _urlStatus;
public Status UrlStatus
{
get { return _urlStatus; }
set
{
if (_urlStatus != value)
{
_urlStatus = value;
OnPropertyChanged("UrlStatus");
}
}
}
private string _color;
public string Color
{
get { return _color; }
set
{
if (_color != value)
{
_color = value;
OnPropertyChanged("Color");
}
}
}
private ObservableCollection<ChildUrl> _childUrlsValue = new ObservableCollection<ChildUrl>();
public ObservableCollection<ChildUrl> ChildUrls
{
get
{
return _childUrlsValue;
}
set
{
_childUrlsValue = value;
}
}
/// <summary>
/// Конструктор класса Url.
/// </summary>
public Url(string absoluteUrl, int responseStatusCode, string responseStatusDescription, Status urlStatus, string color)
{
this.AbsoluteUrl = absoluteUrl;
this.ResponseStatusCode = responseStatusCode;
this.ResponseStatusDescription = responseStatusDescription;
this.UrlStatus = urlStatus;
this.Color = color;
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
ObservableCollection can update your UI automaticaly by using binding. Use a list of ObservableCollection and add / remove items from is. Make the ObservableCollection as a public property.In the MainWindow constructor write:
This.DataContext=This;
Use binding to your listBox / any other control you need to show the items on. ObservableCollection allready implement IINotifyPropertyChanged in it. Once you change the items in your ObservableCollection your UI will change as well.