How to build a TimePicker.TimeChanged Event in c#? - c#

in my tool I create a TimePicker XAML control while runtime, but I'm struggling with the TimeChanged Event.
// TimePicker
TimePicker timePicker = new TimePicker
{
Margin = new Thickness(0, 0, 0, 7),
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Bottom,
RequestedTheme = ElementTheme.Dark,
Name = "Schedule_" + lightnumber + "_timepicker",
ClockIdentifier = "24HourClock",
Time = TimeSpan.Parse(hue_schedules_localtime),
};
hueGrid.Children.Add(timePicker);
timePicker.TimeChanged += new TimePickerValueChangedEventArgs(Schedule_TimeChange);
private void Schedule_TimeChange(string sender, TimePickerValueChangedEventArgs e)
{
}
I always get this error message "Error CS1729 'TimePickerValueChangedEventArgs' does not contain a constructor that takes 1 arguments"
Unfortunately I didn't found an c# example on the internet.
Can somebody please help me with this problem.

You have a mistake in subscribing event code, you should add method/local function/lambda as subscriber, while you're trying to add TimePickerValueChangedEventArgs instance as subscriber instead, and TimePickerValueChangedEventArgs constructor doesn't accept one parameter, so that's why you got TimePickerValueChangedEventArgs does not contain a constructor that takes 1 arguments error. Fixed code:
timePicker.TimeChanged += Schedule_TimeChange;
private void Schedule_TimeChange(object sender, TimePickerValueChangedEventArgs e)
{
}

Related

Add Click event to my dynamically created Xaml Button

I'm currently writing a function that creates button in XAML (on runtime) according to JSON information that is received from an API call in C#.
I currently have the following code:
Button downloadButton = new Button();
downloadButton.Click += new RoutedEventHandler(DownloadContent);
But I get the following error:
An object reference is required for the non-static field, method, or
property 'Mainwindow.DownloadContent(object, RoutedEventArgs)'
I've tried changing it to downloadButton.Click += new RoutedEventHandler(this, DownloadContent); but that gives me the error:
Keyword 'this' is not valid in a static property, static method, or static field initializer
For reference this is what DownloadContent looks like
private void DownloadContent(object sender, RoutedEventArgs e)
{
WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri("API-URL"), contentZip);
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(InstallContent);
}
This is what I want the button to look like (skipping the other stuff like background color, etc.)
<Button Name="Downloadbutton"
Content="Download"
Click="DownloadContent"
</Button>
Am I missing something as why I get this Error and how could I fix it?
EDIT
The Installcontent function looks like this:
private void InstallContent(object sender, AsyncCompletedEventArgs e)
{
ZipFile.ExtractToDirectory(contentZip, contentPath, true);
File.Delete(contentZip);
writeJsonData(DLCbuttonTag);
Downloadbutton.Visibility = Visibility.Collapsed;
Uninstallbutton.Visibility = Visibility.Visible;
}
The function that creates the button:
public static void getContentList()
{
string jsonString = File.ReadAllText(#"C:\Users\stage\OneDrive\Documenten\ContentInfo.json")
ContentList contentList = JsonConvert.DeserializeObject<ContentList>(jsonString);;
for (int i = 0; i < contentList.Content.Count; i++)
{
StackPanel dynamicStackPanel = new StackPanel();
dynamicStackPanel.Orientation = Orientation.Horizontal;
dynamicStackPanel.Background = Brushes.Transparent;
Button downloadButton = new Button();
downloadButton.Click += new RoutedEventHandler(DownloadContent);
dynamicStackPanel.Children.Add(downloadButton);
}
}
The problem is that getContentList is declared as static. You try to reference the method DownloadContent which is an instance method. Remove the static from getContentList to fix the error.
The reason for the error is that static methods cannot access instance members. Static members do not run in the context of a particular instance, but in the context of the type itself. While in the case of WPF there most likely is no other instance of your page, in theory there could be many. The static method would not know which instance to pick, hence the error.
See this link for details on static members.
As a sidenote: in C#, methods are usually started with a capital letter (Pascal casing) regardless of their access modifier. So getContentList would be GetContentList.

How to access Form textboxes inside EventHandler by string in C#?

I am using Visual Studio 2017. There is a form with textboxes. These textboxes need a refresh every 10 seconds. For achieving this I use a Timer event.
public partial class status_window : Form
{
public status_window()
{
InitializeComponent();
shutdown_button.Click += new EventHandler(shutdown_click);
Timer timer = new Timer();
timer.Interval = (1 * 10000); // 10 secs
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
}
The timer_tick function is member of the status_window class. Inside that eventhandler I can access the textboxes by their name as expected. But how to do that if the textbox "adress" is i variable. Look:
private void timer_Tick(object sender, EventArgs e)
{
Int32 unixtime = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
// for all boxes per exname
for (int i = 0; i < something.Count() ; i++)
{
// try to find textbox 1 -> embty result
Console.WriteLine( this.Controls.Find("nam1_last_event", true) );
Console.WriteLine( this.Controls.Find("nam2_last_event", true) ); // also empty result
// this works and fills the formbox as ecxpected
nam1_last_event.Text = "somevalue";
nam1_event_count.Text = "anothervale";
nam2_last_event.Text = "somemorevalue";
nam2_event_count.Text = "andsoon";
// thats what i want later to use my for loop for those:
// something[i] exuals to nam1,nam2 and so on
this.Controls.Find( String.Format("{0}_last_event", something[i].ToLower()) , true)[0].Text = "somevalue"; // this fails cause array returned by find is empty
this.Controls.Find(String.Format("{0}_last_event", ex_name.ToLower()), true)[0].Text = "anothervale"; // same
}
}
So I stuck here somehow limited by my own knowledge. Most results on Google suggest to use the controls Find Method.
This works for me:
var inPanel = this.Controls.Find("inPanel", true).OfType<TextBox>().FirstOrDefault();
inPanel?.Text = "Found it";
In your code you use equally name nam1_last_event as member of class status_window and name of control. Please check in designer if your control relay has name nam1_last_event.
Function Controls.Find use key which is value of property Name of control.
Create a list or Dictionary variable to save those textboxs, and get it in the timer_Tick.

c# Event handler no overide

I have started a new job, where the last dev left they want a program he started to be finished .
I have got to this problem and have looked at it for half a day.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
logTimer = new System.Windows.Threading.DispatcherTimer();
logTimer.Tick += new EventHandler(logTimer_Tick);
logTimer.Interval = new TimeSpan(0, 0, 0, 1);
logTimer.Start();
txtLogData.Text = Logger.GetLines();
try
{
DataProcessor gaugeProcessor = new DataProcessor(SQLConnectionString);
gaugeProcessors.Add(gaugeProcessor);
grdProcessor.ItemsSource = gaugeProcessors;
List<GaugePort> ports = SQLClient.GetGaugePorts(SQLConnectionString);
foreach(GaugePort port in ports)
{
GaugePortListener newListener = new GaugePortListener(port);
listeners.Add(newListener);
}
grdPorts.ItemsSource = listeners;
}
catch(Exception ex)
{
}
}
I am getting an error on line 4 "No Overload for ' logTimer_Tick' matches delegates 'Event Handler'"
The Function it calls dose exist and looks like this
private void logTimer_Tick(object sender, EventArgs e)
{
txtLogData.Text = Logger.GetLines();
}
I have had a look at the links below but i have drawn a blank
http://www.yoda.arachsys.com/csharp/threads/parameters.shtml
C# method name expected
Any ideas would be great
Thanks in advance
EDIT
Change the wording for the error message "Typo"
Directly use the method:
logTimer.Tick += logTimer_Tick;
This should help, as the compiler does strange things with your EventHandler.
The weird thing is that your code seems to work on my machine - that means the code you posted isn't equal to the code you tried or it's a bug caused by your compiler. Or, as a third possibility, the logtimer isn't a WinForms timer, then I can't reproduce your problem.
In this third case it may be possible that the second parameter isn't an EventArg (even though it'd be strange that it works if you don't use the EventHandler stuff). Then you could try an object as second parameter:
private void logTimer_Tick (object sender, object e)
It seems to be neccessary for Windows phone 8.1 (No overload for 'method' matches delegate 'System.EventHandler').

Storyboard.Completed Event Handler Preventing Code From Executing

I am trying to create a simulation program that animates based on the user's input. I am running into an error when I try and create an eventhandler for mystoryboard.completed event. I have read numerous different API articles and forum posts on eventhandling and storyboards but I can't seem to find the cause of my error.
My code compiles and the window displays but anything after the line where I set up the eventhandler doesn't get executed. My MainWindow where I set everything up is shown below.
public MainWindow()
{
InitializeComponent();
titleTextBlock.Text = "MainWindow()";
//this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
mainSystem = new BalanceSystem(3);
leftBlock = new SystemComponents.Block(0, 100, 150, 100, mainSystem);
rightBlock = new SystemComponents.Block(1, 100, 150, 100, mainSystem);
balanceBeam = new SystemComponents.Bar(0, 0, 250, 150, 100, mainSystem);
mainSystem.addComponent(leftBlock, leftWeight);
mainSystem.addComponent(rightBlock, rightWeight);
mainSystem.addComponent(balanceBeam, balanceBar);
titleTextBlock.Text = "LOADED";
}
The constructor for "BalanceSystem" is when things start to go wrong. It steps into the constructor shown below:
public BalanceSystem(int count)
{
componentCount = count;
masterTimeline = new MovementTimeline(1);
}
After entering the constructor for "BalanceSystem" it moves on to the constructor for my custome class "MovementTimeline". The line that breaks everything is the creation and subscription of the eventhandler for masterStoryboard.Completed.
class MovementTimeline
{
private Storyboard masterStoryboard;
private Duration systemDuration;
public MovementTimeline(int totalTime)
{
systemDuration = new Duration(TimeSpan.FromSeconds(totalTime));
masterStoryboard.Completed += new EventHandler(masterStoryboard_Completed);
}
void masterStoryboard_Completed(object sender, EventArgs e)
{
masterStoryboard.Children.Clear();
//masterStoryboard.Completed -= masterStoryboard_Completed;
}
}
Once the compiler or program hits the line where the new EventHandler is created it stops executing the rest of my code and loads the window as is. I cannot for the life of me figure out why this is happening.
it looks to me like you are adding an eventhandler without ever creating a StoryBoard object

Compiler error when creating IntegerUpDown ValueChanged event

I'm using the IntegerUpDown control from WPFExtendedToolkit
However, I'm unable to assign the event my function so that when the value is changed it will call my function. I'm pretty new to both c# and wpf so help is greatly appreciated. I've been trying to get it to work as show in a similar example here.
private IntegerUpDown m_argumentUpDown;
public IntArgumentOption(ArgumentOptionDescription argumentDesc) : base(argumentDesc)
{
m_argumentUpDown = new IntegerUpDown
{
Watermark = argumentDesc.m_watermark,
Increment = (int)argumentDesc.m_interval,
Minimum = (int)argumentDesc.m_minimum,
Maximum = (int)argumentDesc.m_maximum,
FormatString = "G",
SelectAllOnGotFocus = true,
MinWidth = 50,
FontSize = 10,
Margin = new System.Windows.Thickness(5, 0, 0, 0),
};
// COMPILER ERROR:
m_argumentUpDown.ValueChanged += new RoutedPropertyChangedEventHandler<int>(ArgumentChanged);
}
void ArgumentChanged(object sender, RoutedPropertyChangedEventArgs<int> e)
{
}
Doing this results in the compiler error:
error CS0029: Cannot implicitly convert type 'System.Windows.RoutedPropertyChangedEventHandler< int >' to 'System.Windows.RoutedPropertyChangedEventHandler< object >'
Here in the UpDownBase class (Xceed.wpfToolkit.dll) the method signature for ValueChanged is:
public event RoutedPropertyChangedEventHandler<object> ValueChanged;
hence in your code you have to declare a event handler where the generic is of type "Object" instead of int. Because of the mismatch in type the compiler is unable to implicitly convert to Int from object.
So change code as below
m_argumentUpDown.ValueChanged += new RoutedPropertyChangedEventHandler<object>(ArgumentChanged);
}
void ArgumentChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
//type caste e.newValue and e.OldValue
}
The following will work, I tested that. But I dont know if this is considered work around or creator of IntegerUpDown control meant it to be used this way.
m_argumentUpDown.ValueChanged += new RoutedPropertyChangedEventHandler<object>(ArgumentChanged);
//or you can change above line to following for brevity. ReSharper always suggesting me to do this
//m_argumentUpDown.ValueChanged += ArgumentChanged;
void ArgumentChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
//you need to cast New and Old value to int since both are of type object now
int newVal = (int)e.NewValue;
int oldVal = (int)e.OldValue;
}

Categories