I want to handle a clickbutton event from another page - c#

I have two pages MainPage and PlayPage.Inside MainPage I have a frame and a textblock and inside the frame I have Playpage. When I click a button from play page I change a variable but the textblock doesn't update. How do I do that?
Here is my code:
public class Swag
{
public static int swag = 0;
public void Add(int a)
{
swag += a;
}
public void Reduce(int a)
{
swag -= a;
}
public int Get()
{
return swag;
}
}
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
MyFrame.Navigate(typeof(PlayPage));
SwagMeasurer.Text = Convert.ToString(Swag.Get());
}
}
public sealed partial class PlayPage : Page
{
public PlayPage()
{
this.InitializeComponent();
}
private void Clicker_Click(object sender, RoutedEventArgs e)
{
Swag.swag += 1;
}
}

Handling and Raising Events should be your new friend!
Swag :
public class Swag
{
private static int _swag;
public static void Add(int a)
{
_swag += a;
OnUpdate?.Invoke(new SwagEventArgs(a));
OnAddition?.Invoke(new SwagEventArgs(a));
}
public static void Reduce(int a)
{
_swag -= a;
OnUpdate?.Invoke(new SwagEventArgs(a));
OnSubtraction?.Invoke(new SwagEventArgs(a));
}
public static int Get()
{
return _swag;
}
public static event AddedValueEventHandler OnAddition;
public static event SubtractedValueEventHandler OnSubtraction;
public static event UpdatedValueEventHandler OnUpdate;
public delegate void AddedValueEventHandler(SwagEventArgs e);
public delegate void SubtractedValueEventHandler(SwagEventArgs e);
public delegate void UpdatedValueEventHandler(SwagEventArgs e);
}
Keep in mind, that privacy should be respected!
PlayPage :
public partial class PlayPage : Page
{
public PlayPage()
{
InitializeComponent();
}
private void Clicker_Sub_Click(object sender, RoutedEventArgs e)
{
Swag.Reduce(1);
}
private void Clicker_Add_Click(object sender, RoutedEventArgs e)
{
Swag.Add(1);
}
}
Please note, that I have added a subtraction Button.
MainWindow :
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
MyFrame.Navigate(new PlayPage());
SwagMeasurer.Text = Convert.ToString(Swag.Get());
Swag.OnAddition += Swag_Addition;
Swag.OnSubtraction += Swag_OnSubtraction;
Swag.OnUpdate += Swag_OnUpdate;
}
private void Swag_OnUpdate(SwagEventArgs e)
{
SwagMeasurer.Text = Convert.ToString(Swag.Get());
}
private void Swag_OnSubtraction(SwagEventArgs e)
{
LastMode.Text = "That's a negative";
}
private void Swag_Addition(SwagEventArgs e)
{
LastMode.Text = "That's a positive";
}
}
LastMode is also a TextBlock (reprecenting if the user has dropped or raised his skill level).
SwagEventArgs :
public class SwagEventArgs : EventArgs
{
public SwagEventArgs(int value)
{
Value = value;
}
public readonly int Value;
}
SwagEventArgs is going to be used to store information as event data.

Related

C# EventHandler returns null when called

I have a two classes.In one class i am creating and raising an event as follows :
CustomerAdd Class
public class CustomerAdd
{
public delegate void Done(object Sender, EventArgs e);
public event Done ListUpdated;
public void UpdateNewList()
{
//adding items to a generic List<T>,code removed as not relevant to post
//and raising the event afterwards
if (ListUpdated != null)
{
ListUpdated(this, EventArgs.Empty);
}
}
}
MyWindow Class
public class MyWindow
{
private void SaveToDisk()
{
CustomerAdd cuss = new CustomerAdd();
cuss.ListUpdated += new CustomerAdd.Done(DisplayDetails);
cuss.UpdateNewList();
}
private void DisplayDetails()
{
//other codes here
}
}
Now, when i call the SaveToDisk method from MyWIndow class,(as i am subscribing DisplayDetails method to the ListUpDated event) , DisplayDetails is not called. The debugger shows that ListUpdated is null. I have searched for hours and failed to come up with a solution.I followed this link but still ListUpdated is null. Any guidance/help would be highly appreciated.
It works:
using System;
namespace ConsoleApp2
{
class Program
{
public class CustomerAdd1
{
public delegate void Done(object Sender, EventArgs e);
public event Done ListUpdated;
public void UpdateNewList()
{
//adding items to a generic List<T>,code removed as not relevant to post
//and raising the event afterwards
if (ListUpdated != null)
{
ListUpdated(this, EventArgs.Empty);
}
}
}
public class CustomerAdd
{
public void SaveToDisk()
{
CustomerAdd1 cuss = new CustomerAdd1();
cuss.ListUpdated += new CustomerAdd1.Done(DisplayDetails);
cuss.UpdateNewList();
}
private void DisplayDetails(object Sender, EventArgs e)
{
Console.WriteLine("Test");
}
}
static void Main(string[] args)
{
var c = new CustomerAdd();
c.SaveToDisk();
Console.ReadLine();
}
}
}
Try this:
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
CustomerReceive cr = new CustomerReceive();
cr.SaveToDisk();
}
}
public class CustomerAdd
{
public delegate void Done(object Sender, EventArgs e);
public event Done ListUpdated;
public void UpdateNewList()
{
//adding items to a generic List<T>,code removed as not relevant to post
//and raising the event afterwards
if (ListUpdated != null)
{
ListUpdated.Invoke(this, EventArgs.Empty);
}
}
}
public class CustomerReceive
{
public void SaveToDisk()
{
CustomerAdd cuss = new CustomerAdd();
cuss.ListUpdated += new CustomerAdd.Done(DisplayDetails);
cuss.UpdateNewList();
}
private void DisplayDetails(object Sender, EventArgs e)
{
int k = 0;
}
}
}
You need to do a good read on delegates and events because this is not working when there are more listeners

Create EventHandler and listen to Event from another class

I've created event as bellow and want to listen to it and execute method in another class when it fires
but saveEvent always comes to be null and it doesn't fire
I don't know what I've missed
here's my first class has button
internal partial class OpenSaveReportWizardForm : Form
{
public event EventHandler saveEvent;
private void saveButton_Click(object sender, EventArgs e)
{
saveEvent?.Invoke(this, e);
}
}
and here's the second class where I want to listen to saveEvent
internal class Database
{
public Database()
{
Program._wizardForm.saveEvent += (sender, e) => HandleSaveMethod( );
}
public void HandleSaveMethod()
{
// do something
}
here's where I open the form
internal class Program
{
public static OpenSaveReportWizardForm _wizardForm;
private static void Main()
{
OpenFileCommandHandler();
}
void OpenFileCommandHandler()
{
_wizardForm = new OpenSaveReportWizardForm( );
_wizardForm.ShowDialog();
}
}
Because you disposed wizardForm, after that event is cleared.
You should write next code:
internal class Database
{
private bool _isDisposed;
private OpenSaveReportWizardForm _wizardForm;
public Database()
{
_wizardForm = new OpenSaveReportWizardForm(m_Opening,m_ConnectionProperties,m_ColumnProperties))
_wizardForm.saveEvent += (sender, e) => HandleSaveMethod( );
}
public void HandleSaveMethod()
{
// do something
}
public void Dispose()
{
if(_isDisposed)
return;
_isDisposed = true;
_wizardForm.saveEvent -= HandleSaveMethod;
_wizardForm.Dispose();
}

Winforms MVP show mdi child form

Guys i have problem with MVP design pattern becouse am not shure how can i show child view in parent form.
My view does not have MdiParent property. Can i manually create it in view interface?
Very ugly look to every form opens in a new window!
I have two presenters:
MainPresenter (represent mainForm(parent) logic)
TaskPresenter (represent logic for save,insert,delete logic)
Two View interfaces:
IMainView
ITaskView
And two winforms:
MainForm - mainwindow(parrent mdi form)
TaskForm
Check code:
MainPresenter
public class MainPresenter
{
private readonly IMainView view;
private List<ITaskModel> tasks;
// Constructor
public MainPresenter(IMainView view)
{
this.view = view;
this.Init();
this.tasks = new List<ITaskModel>();
}
// Initialize
private void Init()
{
this.view.AddTask += AddTask;
}
// Add task
private void AddTask(object sender, EventArgs e)
{
// Show as MDI CHILD
}
}
IMainView
public interface IMainView
{
event EventHandler<EventArgs> AddTask;
}
TaskPresenter
public class TaskPresenter
{
private readonly ITaskView view;
private List<ITaskModel> tasks;
private bool isNew = true;
private int currentIndex = 0;
// Constructor
public TaskPresenter(ITaskView view)
{
this.view = view;
this.Initialize();
}
// Initialize
public void Initialize()
{
tasks = new List<ITaskModel>();
view.SaveTask += Save;
view.NewTask += New;
view.PrevTask += Previous;
view.NextTask += Next;
}
private void Save(object sender, EventArgs e)
{
}
private void New(object sender, EventArgs e)
{
}
private void Next(object sender, EventArgs e)
{
}
private void Previous(object sender, EventArgs e)
{
}
private void BlankTask()
{
}
private void LoadTask(ITaskModel task)
{
}
}
ITaskView
public interface ITaskView
{
String TaskName { get; set; }
String TaskPriority { get; set; }
DateTime? StartDate { get; set; }
DateTime? DuoDate { get; set; }
event EventHandler<EventArgs> SaveTask;
event EventHandler<EventArgs> NewTask;
event EventHandler<EventArgs> NextTask;
event EventHandler<EventArgs> PrevTask;
}
And here is MainForm
public partial class MainForm : Form, IMainView
{
MainPresenter Presenter;
// Construcor
public MainForm()
{
InitializeComponent();
}
// Events
public event EventHandler<EventArgs> AddTask;
// On load
private void MainForm_Load(object sender, EventArgs e)
{
Presenter = new MainPresenter(this);
}
// On click add task btn
private void addTaskBtn_Click(object sender, EventArgs e)
{
if(AddTask != null)
{
// When is this event triggered i want to show another child form for adding new task
AddTask(this, EventArgs.Empty);
}
}
}
So how can i show TaskView as child in MainView?
UIApplication it is Windows Forms Application but output type Class Library.
Add referance MVPFramework
MainForm
public partial class MainForm : Form , IMainView
{
[Resolve]
public IMainControl mainControl;
public MainForm()
{
InitializeComponent();
}
public bool ShowAsDialog()
{
throw new NotImplementedException();
}
private void openChildFormToolStripMenuItem_Click(object sender, EventArgs e)
{
mainControl.OnOpenChildForm();
}
}
Child Form
public partial class ChildForm : Form , IChildView
{
public ChildForm()
{
InitializeComponent();
}
public bool ShowAsDialog()
{
throw new NotImplementedException();
}
public object MDIparent
{
set
{
this.MdiParent = (Form)value;
}
}
}
CoreApplication it is class Library
IMainControl
public interface IMainControl :IControl
{
void OnOpenChildForm();
}
MainControl
public class MainControl :IMainControl
{
[Resolve]
public IApplicationController applicationController;
public void OnOpenChildForm()
{
IChildControl TransfersOnTheWayControl = applicationController.Resolve<IChildControl>();
TransfersOnTheWayControl.Run();
}
}
IChildControl
public interface IChildControl :IControl
{
void Run();
}
IMainView
public interface IMainView :IView
{
}
IChildView
public interface IChildView :IView
{
bool ShowAsDialog();`enter code here`
object MDIparent { set; }
}
IMainPresenter
public interface IMainPresenter :IPresenter
{
}
IChildPresenter
public interface IChildPresenter :IPresenter
{
bool Ask();
}
MainPresenter
public class MainPresenter :BasePresenter<IMainView>, IMainPresenter
{
}
ChildPresenter
public class ChildPresenter : BasePresenter<IChildView>, IChildPresenter
{
public bool Ask()
{
this.Init();
bool res = View.ShowAsDialog();
ApplicationController.ClearInstance<IChildView>();
return res;
}
public override void Init()
{
View.MDIparent = ApplicationController.GetMainFrom<IMainPresenter>();
base.Init();
}
}
LauncherApplication it is Console Application but output type Windows Form.
class Program
{
static void Main(string[] args)
{
IApplicationController applicationController = new ApplicationController(new ServicesContainerAdapter());
applicationController
//RegisterView
.RegisterView<IMainView, MainForm>()
.RegisterView<IChildView, ChildForm>()
//RegisterPresenter
.RegisterPresenter<IMainPresenter, MainPresenter>()
.RegisterPresenter<IChildPresenter, ChildPresenter>()
//RegisterController
.RegisterController<IMainControl, MainControl>()
.RegisterController<IChildControl, ChildControl>();
IMainPresenter mainPresenter = applicationController.Resolve<IMainPresenter>();
mainPresenter.Init();
Application.Run((Form)mainPresenter.FormObject);
}
}

using events for passing parameters

In my code,I have a button and a textbox. I want by clicking on the button, the value of the variable k to be sent to the textbox. but when I click on the button nothing happens what's wrong with my code.
here's my code.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public delegate string fac(int x);
public static fac intostring = factory;
public static string inst= null;
public static string factory(int x)
{
inst = x.ToString();
return inst;
}
public delegate void myeventhandler(string newvalue);
public class EventExample
{
private string thevalue;
public event myeventhandler Valuechanged;
public string val
{
set
{
this.thevalue = value;
this.Valuechanged(thevalue);
}
}
}
public void uu(string newvalue)
{
this.textBox1.Name = (newvalue);
}
static int k=0;
private void button1_Click(object sender, EventArgs e)
{
k = 1;
intostring(k);
}
private void Form1_Load(object sender, EventArgs e)
{
EventExample myevt = new EventExample();
myevt.Valuechanged += new myeventhandler(uu);
myevt.val = inst;
}
}
}
Simply set it inside of button1_Click
private void button1_Click(object sender, EventArgs e)
{
k = 1;
intostring(k);
this.textBox1.Text = thevalue;
}

how to access winform components from another class?

i have a form with one button and two labels
and i have a separate class called myCounter
i want the myCounter class to be able to access the labels in the form
through a method called changeColor..
how can make the labels available in this class
the form
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Color colTurn
{
get { return lblp1Turn.BackColor; }
set { lblp1Turn.BackColor = value; }
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
the class
class myCounter
{
private readonly Form1 Board;
public myCounter(Form1 Board)
{
this.Board = Board;
}
public int turn = 0;
public void changeColor()
{
if (turn == 0)
{
turn = 1;
lbl
//change color code here
}
}
}
So it looks like you're passing the whole form into your second class anyway, So I'd do what LightStriker suggested. Make a public accessor for all of your items and then set it in your other class.
public partial class Form1 : Form
{
private myCounter _counterClass;
public Form1()
{
InitializeComponent();
}
public Label MyLabel1
{
get {return mylabel1;}
}
public Label MyLabel2
{
get {return mylabel2;}
}
private void Form1_Load(object sender, EventArgs e)
{
_counterClass = new myCounter(this);
}
protected void ButtonClick(object sender, EventArgs e)
{
_counterClass.changeColor();
}
}
Then in your second class you have access to your Label.
class myCounter
{
private readonly Form1 Board;
public myCounter(Form1 Board)
{
this.Board = Board;
}
public int turn = 0;
public void changeColor()
{
if (turn == 0)
{
turn = 1;
Board.MyLabel1.BackColor = Color.Red;
Board.MyLabel2.BackColor = Color.White;
}
else
{
turn = 0;
Board.MyLabel2.BackColor = Color.Yellow;
Board.MyLabel1.BackColor = Color.White;
}
}
}
Keep in mind this is code I have written in a wiki markup editor and is untested. This SHOULD work for you though.
Create a public method on your form for this.
public partial class Form1 : Form{
public void SetLabelColor(Color color){
mylabel.BackColor = color;
}
//... Other code
}

Categories