假设我的WPF应用程序中有两个类:
Vehicle
...其中Radio
有一个属性,它是private void startButton_Click(object sender, TextChangedEventArgs e)
{
Vehicle Xterra = new Vehicle() { MusicRadio = new Radio() };
for (int i = 0; i < 666; i++)
{
Xterra.MusicRadio.Volume = i;
}
}
类的一个实例。在我的代码中,我想在单击按钮时设置该无线电类的音量:
Explode()
在上面的代码中,一旦for循环达到10次迭代,应用程序应该通过Vehicle
方法关闭。
每次Explode()
属性更改时,我希望我的MusicRadio
类执行其私有函数{{1}}。我如何确保提醒这一变化?
答案 0 :(得分:0)
执行此操作的一种方法是向Radio
课程添加Vehicle
个活动。然后在Explode
课程中,您可以订阅该活动并从那里致电public class Radio
{
private int volume;
public int Volume
{
get { return volume; }
set
{
if (value == volume) return;
volume = value;
OnVolumeChanged(new EventArgs());
}
}
public event EventHandler VolumeChanged;
protected virtual void OnVolumeChanged(EventArgs e)
{
VolumeChanged?.Invoke(this, e);
}
}
。 注意我还没有使用wpf,我只是假设它会在那里工作。如果不是这样的话,很高兴删除答案。
首先,将事件添加到Radio类:
Explode
然后,在Vehicle类中订阅它,并从那里调用Explode
(或直接将public class Vehicle
{
private Radio musicRadio;
public Radio MusicRadio
{
get { return musicRadio; }
set
{
musicRadio = value;
if (musicRadio != null)
{
// In the unlikely event that the same radio is assigned more than once,
// we only want to subscribe to the event one time, so remove it first.
musicRadio.VolumeChanged -= MusicRadio_VolumeChanged;
musicRadio.VolumeChanged += MusicRadio_VolumeChanged;
}
}
}
private void MusicRadio_VolumeChanged(object sender, EventArgs e)
{
Explode();
}
private void Explode()
{
if (MusicRadio.Volume == 10)
{
Application.Shutdown();
}
}
}
代码移动到事件中):
| id | movie | value |
|----|-------|-------|
| 1 | a | 0 |
| 2 | a | 0 |
| 3 | a | 20 |
| 4 | a | 0 |
| 5 | a | 10 |
| 6 | a | 0 |
| 7 | a | 20 |
| 8 | b | 0 |
| 9 | b | 0 |
| 10 | b | 30 |
| 11 | b | 30 |
| 12 | b | 30 |
| 13 | b | 10 |
| 14 | c | 40 |
| 15 | c | 40 |
答案 1 :(得分:-1)
WPF MVC
视图模型:
public abstract class ObservableObject : INotifyPropertyChanged, INotifyDataErrorInfo
{
public void OnPropertyChanged<T>(Expression<Func<T>> property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property.GetMemberInfo().Name));
}
}
}
public class TankModel : ObservableObject
{
public float Level
{
get { return level; }
set
{
try
{
if (level != value)
{
level = value;
OnPropertyChanged(() => Level);
}
}
catch (Exception ex)
{
log.Error(ex);
}
}
}
}