gpt4 book ai didi

c# - 检查父属性是否已更改

转载 作者:行者123 更新时间:2023-11-30 23:05:19 24 4
gpt4 key购买 nike

我创建了一个继承自 System.Windows.Forms.Timer 的新类。在此类中,我创建了另一个计时器作为属性,该属性由父类的计时器启用。子定时器定时器然后报告时间直到下一个父时钟。

我想避免必须使用另一种方法来启动两个计时器。

我能以某种方式检查父 timer.enabled 是否已更改吗?这里的问题是,如果我启动父计时器,我必须等待 timer.Interval 直到它第一次计时。但我希望子计时器从父计时器开始报告第一个滴答的时间。

这是我到目前为止所得到的。

public class LoopTimer : Timer {

public DateTime? NextTickSchedule { get; set; }

public LoopTimer() : base() {
CountdownTimer.Interval = 1000;
CountdownTimer.Tick += CountdownTimer_Tick;
this.Tick += LoopTimer_Tick;
}

public LoopTimer(IContainer container) : base(container) {
CountdownTimer.Interval = 1000;
}

private void LoopTimer_Tick(object sender, EventArgs e) {
OnTick();
}

private void OnTick() {
NextTickSchedule = DateTime.Now.AddMilliseconds(this.Interval);
MinutesUntilNextTick = TimeUntilNextTick.ToString("mm\\:ss");
}

public void StartTimer() {
this.Enabled = CountdownTimer.Enabled = true;
OnTick();
}

public void StopTimer() {
this.Enabled = CountdownTimer.Enabled = false;
NextTickSchedule = null;
MinutesUntilNextTick = "";
TimeUntilNextTick = new TimeSpan();
}

#region Countdown Timer

public Timer CountdownTimer { get; set; } = new Timer();
public TimeSpan TimeUntilNextTick { get; set; } = new TimeSpan();
public string MinutesUntilNextTick { get; set; } = "";

private void CountdownTimer_Tick(object sender, EventArgs e) {
if (NextTickSchedule.HasValue) {
TimeUntilNextTick = NextTickSchedule.Value - DateTime.Now;
MinutesUntilNextTick = TimeUntilNextTick.ToString("mm\\:ss");
}
}

#endregion
}

最佳答案

您可以覆盖 Enabled 属性并在启用更改时引发事件。然后在子/其他控件中,订阅该事件:

public class MyTimer : Timer
{
public event EventHandler EnabledChanged;
public override bool Enabled
{
get { return base.Enabled; }
set
{
base.Enabled = value;
EnabledChanged?.Invoke(this, EventArgs.Empty);
}
}
}

关于c# - 检查父属性是否已更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48901517/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com