/* class library /
/ calcEventArgs.cs */
namespace calc1
{
public class calcEventArgs
{
}
public class CalculationCompletedEventArgs : System.EventArgs
{
public string StringValue { get; set; }
public int IntegerValue { get; set; }
}
}
/* CalcMain.xaml.cs */
namespace calc1
{
public partial class CalcMain : Page
{
public delegate void CalcEventHandler(object sender, CalculationCompletedEventArgs e);
public event CalcEventHandler CalculateCompletedEvent;
public CalcMain()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
CalculationCompletedEventArgs pArgs = new CalculationCompletedEventArgs();
pArgs.StringValue = "1 + 1";
pArgs.IntegerValue = 2;
CalcEventHandler eh = CalculateCompletedEvent;
if (eh != null) eh(this, pArgs);
}
}
}
/* EventTest application program */
namespace EventTest
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
calc1.CalcMain c = new calc1.CalcMain();
c.CalculateCompletedEvent += new calc1.CalcMain.CalcEventHandler(CalcfromPage);
}
private void CalcfromPage(object sender, calc1.CalculationCompletedEventArgs e)
{
MessageBox.Show(e.StringValue + " = " + e.IntegerValue.ToString());
}
private void Button_Click(object sender, RoutedEventArgs e)
{
fraMainScreen.Navigate(new Uri("pack://application:,,,/calc1;component/CalcMain.xaml", UriKind.Absolute));
}
}
}
this is my code
i have problem ...
CalcEventHandler eh = CalculateCompletedEvent
CalculateCompletedEvent is always null..
help..
thanks. ^^
Related
I want my price calculation to alter as I type, however the calculation is delayed.
My class is as follows
using System;
using System.Windows.Forms;
namespace MyClass
{
public class Model
{
public decimal Cost { get; set; }
public decimal MarkUp { get; set; }
public decimal Price { get; set; }
public decimal CalculatedPrice => Cost * (1 + MarkUp / 100);
}
public partial class FormTest : Form
{
public Model model { get; set; }
public FormTest()
{
InitializeComponent();
model = new Model
{
Price = 0,
MarkUp = 0
};
Calculate();
bs.Add(model);
textBoxCost.DataBindings.Add("Text", bs, "Cost", true, DataSourceUpdateMode.OnPropertyChanged);
textBoxMarkUp.DataBindings.Add("Text", bs, "MarkUp", true, DataSourceUpdateMode.OnPropertyChanged);
textBoxPrice.DataBindings.Add("Text", bs, "Price", true, DataSourceUpdateMode.OnPropertyChanged);
}
private void textBoxCost_TextChanged(object sender, EventArgs e)
{
Calculate();
}
private void Calculate()
{
model.Price = model.CalculatedPrice; // does not have the most up to date value
}
private void textBoxMarkUp_TextChanged(object sender, EventArgs e)
{
Calculate();
}
}
}
When I put a break in Calculate I see that the model has not updated.
What do I need to do?
[Update]
I now have the following:
public class Model : INotifyPropertyChanged
{
private decimal _cost;
public decimal Cost {
get => _cost;
set {
_cost = value;
var args = new PropertyChangedEventArgs(nameof(Cost));
PropertyChanged?.Invoke(this,args );
} }
private decimal _markup;
public decimal MarkUp {
get => _markup;
set {
_markup = value;
var args = new PropertyChangedEventArgs(nameof(MarkUp));
PropertyChanged?.Invoke(this, args);
} }
public decimal Price { get; set; }
public decimal CalculatedPrice => Cost * (1 + MarkUp / 100);
public event PropertyChangedEventHandler? PropertyChanged;
}
and
public partial class FormTest : Form
{
public Model model { get; set; }
public FormTest()
{
InitializeComponent();
}
private void Model_PropertyChanged(object? sender, PropertyChangedEventArgs e) { Calculate(); }
private void AddBinding(TextBox textBox, string dataMember)
{
var binding = new Binding(propertyName: "Text", dataSource: bs, dataMember:dataMember);
// binding.Format += Binding_Format; // yet to do
textBox.DataBindings.Add(binding);
}
private void Calculate() {
model.Price = model.CalculatedPrice;
}
private void FormTest_Load(object sender, EventArgs e)
{
model = new Model { Cost = 0, Price = 0, MarkUp = 0 };
model.PropertyChanged += Model_PropertyChanged;
bs.Add(model);
AddBinding(textBoxCost, "Cost");
AddBinding(textBoxMarkUp, "MarkUp");
AddBinding(textBoxPrice, "Price");
}
}
It works when I press Tab to exit a field.
How can I make it work when KeyUp occurs?
The TextChanged event has the same issue.
I tried issuing bs.EndEdit from within the event code but it did not help.
The following works
private void textBoxCost_KeyUp(object sender, KeyEventArgs e)
{
var tb = sender as TextBox;
model.Cost = Convert.ToDecimal( tb.Text);
Calculate();
}
private void textBoxMarkUp_KeyUp(object sender, KeyEventArgs e)
{
var tb = sender as TextBox;
model.MarkUp = Convert.ToDecimal(tb.Text);
Calculate();
}
I have the following code, I would like to call the function RefreshProcess(SaveEventTriggerModelArgs obj) from MainWindow_Loaded.
However the problem I am running into due to lack of knowledge working with window apps I calling this method inside.
It will not let me because of the arguments SaveEventTriggerModelArgs obj and if I add those into RefreshProcess, they are different from void MainWindow_Loaded(object sender, RoutedEventArgs e). How to do it?
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded+= Window_Loaded;
}
private void RefreshProcess(SaveEventTriggerModelArgs obj)
{
var rect = new Rect();
Dispatcher.Invoke(() =>
{
obj.CurrentEventTriggerModel.ProcessInfo = new ProcessInfo()
{
ProcessName = "Nox" != null ? $"Nox" : "",
Position = rect,
};
});
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
}
public class SaveEventTriggerModelArgs : INotifyEventArgs
{
public Model CurrentEventTriggerModel { get; set; }
}
public class MousePointEventArgs : INotifyEventArgs
{
public ViewModel MousePointViewMode { get; set; }
}
public class ViewModel
{
}
public class Model
{
public ProcessInfo ProcessInfo { get;set;}
}
public class ProcessInfo
{
public string ProcessName { get;set;}
public Rect Position { get;set;}
}
Class Icons.cs:
public class Icon
{
public int IconID { get; set; }
public string Title { get; set; }
public string Room { get; set; }
public string ImageCover { get; set; }
}
public class IconManager
{
public static List<Icon> GetIcons()
{
var Icons = new List<Icon>();
Icons.Add(new Icon { IconID = 1, Title = "Mr.Ha", Room = "611-Room", ImageCover = "Assets/Ha.jpg" });
Icons.Add(new Icon { IconID = 2, Title = "Mr.Synh", Room = "611-Room", ImageCover = "Assets/Synh.jpg" });
return Icons;
}
}
Class MainPage:
public MainPage()
{
this.NavigationCacheMode = NavigationCacheMode.Enabled;
this.InitializeComponent();
Icons = IconManager.GetIcons();
}
private void ForegroundElement_ItemClick(object sender, ItemClickEventArgs e)
{
var icon = (Icon)e.ClickedItem;
var tittle = icon.Title;
ForegroundElement.PrepareConnectedAnimation("ca1", icon, "ConnectedElement");
switch (tittle)
{
case "Mr.Ha":
Frame.Navigate(typeof(BlankPage1));
break;
}
}
private async void ForegroundElement_Loaded(object sender, RoutedEventArgs e)
{
if(Icons != null)
{
ForegroundElement.ScrollIntoView(Icons, ScrollIntoViewAlignment.Default);
ForegroundElement.UpdateLayout();
ConnectedAnimation animation = ConnectedAnimationService.GetForCurrentView().GetAnimation("ca2");
if (animation != null)
{
await ForegroundElement.TryStartConnectedAnimationAsync(
animation, Icons, "ConnectedElement");
}
}
Class BlankPage1:
public BlankPage1()
{
this.NavigationCacheMode = NavigationCacheMode.Enabled;
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
ConnectedAnimation imageAnimation = ConnectedAnimationService.GetForCurrentView().GetAnimation("ca1");
if (imageAnimation != null)
{
imageAnimation.TryStart(TargetElement);
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("ca2", TargetElement);
Frame.Navigate(typeof(MainPage));
}
There something wrong with my Animation when I "Navigate Back" to the MainPage. The picture just stay still there then it's disappear, while the listview is done loaded !!My navigation from MainPage to BlankPage1 is fine though!!
Your second connected animation is called ca2, but you are using ca1 in the MainPage's ForegroundElement_Loaded event handler. Because of this, the animation cannot be connected, which results in the behavior you are seeing.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a Flight class and a Form class, I want to send Log messages to a textfield from the Flight class to the Form.
I have an already working one for another class called Airport, but this one is practically identical, yet the event LogMessage is always null, even after subscribing.
-- MainForm --
namespace FlightSim
{
public partial class MainForm : Form
{
Airport airport = new Airport();
Luggage luggage = new Luggage();
Flight flight = new Flight();
DAO db = new DAO();
public MainForm()
{
InitializeComponent();
InitializeEvents();
}
private void InitializeEvents()
{
this.airport.ErrorMessage += new System.EventHandler(OnErrorReceived);
this.flight.LogMessage += new System.EventHandler(OnLogReceived);
}
public void OnErrorReceived(object sender, System.EventArgs e)
{
string msgContent = ((Airport.MessageEventArgs)e).msgContent;
this.mainLog.AppendText(msgContent);
}
public void OnLogReceived(object sender, System.EventArgs e)
{
string msgcontent = ((Flight.MessageEventArgs)e).msgContent;
this.mainLog.AppendText(msgcontent);
}
}
}
-- Flight --
namespace FlightSim
{
public class Flight
{
public class MessageEventArgs : System.EventArgs
{
public string msgContent;
}
public event System.EventHandler LogMessage;
DAO db = new DAO();
public Flight(string flightNumber, string departure, string destination, int totalLoadCapacity)
{
this.FlightNumber = flightNumber;
this.Departure = departure;
this.Destination = destination;
this.TotalLoadCapacity = totalLoadCapacity;
//LogMessage += (s, o) => { };
}
public void StartFlight()
{
string tmpDeparture = this.Departure;
string tmpDestination = this.Destination;
this.OnLogUpdate("Taking off from " + tmpDeparture + " now.");
this.Destination = tmpDeparture;
Thread.Sleep(1000);
this.OnLogUpdate("Arriving in " + tmpDestination + " now.");
this.Departure = tmpDestination;
}
protected void OnLogUpdate(string logMessage)
{
if (logMessage == "")
return;
MessageEventArgs e = new MessageEventArgs();
var handler = LogMessage;
if (handler != null)
{
e.msgContent = logMessage;
handler(this, e);
}
}
}
}
So, what can be the cause for an event being null even though it is subscribed?
Given the constructor with arguments and the initialization without arguments, you probably are creating another Flight class somewhere else. All you have to do is make sure that you subscribe the same event upon creation. Do something like this;
Flight someOtherFlight = new Flight("1", "Amsterdam", "Hong Kong", 500);
someOtherFlight.LogMessage += new System.EventHandler(OnLogReceived);
And you should be fine.
Edit: This MCVE works fine
Program.cs
namespace StackOverflowPlayground
{
class Program
{
static void Main(string[] args)
{
var sim = new AirportSim();
sim.flight.StartFlight();
}
}
}
FlightSim.cs
using System;
using System.Threading;
namespace StackOverflowPlayground
{
public class AirportSim
{
public Flight flight = new Flight("1","","",1);
public AirportSim()
{
InitializeEvents();
}
private void InitializeEvents()
{
flight.LogMessage += OnLogReceived;
}
public void OnLogReceived(object sender, System.EventArgs e)
{
string msgcontent = ((Flight.MessageEventArgs)e).msgContent;
Console.WriteLine(msgcontent);
}
}
public class Flight
{
public class MessageEventArgs : EventArgs
{
public string msgContent;
}
public event EventHandler LogMessage;
public Flight(string flightNumber, string departure, string destination, int totalLoadCapacity)
{
FlightNumber = flightNumber;
Departure = departure;
Destination = destination;
TotalLoadCapacity = totalLoadCapacity;
//LogMessage += (s, o) => { };
}
public string Destination { get; set; }
public int TotalLoadCapacity { get; set; }
public string Departure { get; set; }
public string FlightNumber { get; set; }
public void StartFlight()
{
string tmpDeparture = this.Departure;
string tmpDestination = this.Destination;
OnLogUpdate("Taking off from " + tmpDeparture + " now.");
Destination = tmpDeparture;
Thread.Sleep(1000);
OnLogUpdate("Arriving in " + tmpDestination + " now.");
Departure = tmpDestination;
}
protected void OnLogUpdate(string logMessage)
{
if (logMessage == "")
return;
var e = new MessageEventArgs();
var handler = LogMessage;
if (handler != null)
{
e.msgContent = logMessage;
handler(this, e);
}
}
}
}
This is my class, I always get a null insted of my panel...
Can someone give me a hint on how to do this?
[Serializable]
public class DragDropBlock : Panel
{
public DragDropBlock()
{
this.MouseDown += new MouseEventHandler(Mouse_Down);
this.MouseUp += new MouseEventHandler(Mouse_Up);
}
void Mouse_Down(object sender, System.Windows.Forms.MouseEventArgs e)
{
Clipboard.SetData("DragDropBlock", this);
}
void Mouse_Up(object sender, System.Windows.Forms.MouseEventArgs e)
{
IDataObject IBlock = Clipboard.GetDataObject();
DragDropBlock Block = (DragDropBlock)IBlock.GetData(typeof(DragDropBlock));
}
}
Given a class:
[Serializable]
class Test
{
public string Data
{
get;
set;
}
}
This works:
Test t = new Test()
{
Data = "DERP!"
};
Clipboard.SetData("Test", t);
Test newT = (Test)Clipboard.GetData("Test");
Console.WriteLine(newT.Data);
And if you want to use data objects:
Test t = new Test()
{
Data = "DERP!"
};
Clipboard.SetDataObject(new DataObject("Test", t));
Test newT = (Test)Clipboard.GetDataObject().GetData("Test");
Console.WriteLine(newT.Data);
The output to both of those is:
DERP!
This is the correction of my class: Working!!!
[Serializable]
class DragBlock
{
public string Data
{
get;
set;
}
}
public class DragDropBlock : Panel
{
DragBlock Block;
public DragDropBlock()
{
this.MouseDown += new MouseEventHandler(Mouse_Down);
this.MouseUp += new MouseEventHandler(Mouse_Up);
Block = new DragBlock()
{
Data = "TEST!"
};
}
void Mouse_Down(object sender, System.Windows.Forms.MouseEventArgs e)
{
Clipboard.SetDataObject(new DataObject("DragBlock", Block));
}
void Mouse_Up(object sender, System.Windows.Forms.MouseEventArgs e)
{
DragBlock newBlock = (DragBlock)Clipboard.GetDataObject().GetData("DragBlock");
Console.WriteLine(newBlock.Data);
}
}