我编写了一个 WPF 应用程序,其中 Singleton 类读取光标坐标和使用它的 Observer 类将它们发布在标签中。
在用于读取坐标的 Singleton 类中,我现在使用计时器。我想用 EventAggregator 替换他,它将使用 MouseMoveEvent。我已经阅读了很多教程,但我不明白 EventAggregator 的工作原理以及它如何适合我的应用程序。任何人都可以用我自己的例子来解释吗?这是代码:
单身人士:
public class MousePointProvider
{
[DllImport("user32.dll")]
static extern bool GetCursorPos(ref System.Drawing.Point lpPoint);
private List<IObserver> _observerList;
private DispatcherTimer _timer;
private static MousePointProvider _instance = null;
public static MousePointProvider Instance
{
get
{
if (_instance == null)
{
_instance = new MousePointProvider();
}
return _instance;
}
}
private Point _currentMousePosition;
public Point CurrentMousePosition
{
get { return _currentMousePosition; }
}
private MousePointProvider()
{
_observerList = new List<IObserver>();
_timer = new DispatcherTimer();
_timer.Interval = TimeSpan.FromMilliseconds(1);
_timer.Tick += (s, e) =>
{
MousePositionChanged();
};
_timer.Start();
}
public void RegisterObserver(IObserver observer)
{
if (!_observerList.Contains(observer))
{
_observerList.Add(observer);
}
}
public void UnregisterObserver(IObserver observer)
{
_observerList.Remove(observer);
}
public void MousePositionChanged()
{
GetCursorPos(ref _currentMousePosition);
for (int i = 0; i < _observerList.Count; i++)
{
_observerList[i].MouseChanged(_currentMousePosition.X, _currentMousePosition.Y);
}
}
}
观察员:
public class Listener : Canvas, IObserver
{
System.Windows.Controls.Label labelX = new System.Windows.Controls.Label();
System.Windows.Controls.Label labelY = new System.Windows.Controls.Label();
public Listener()
{
MousePointProvider.Instance.RegisterObserver(this);
this.Children.Add(labelX);
Canvas.SetLeft(labelX, 100);
Canvas.SetTop(labelX, 100);
this.Children.Add(labelY);
Canvas.SetLeft(labelY, 100);
Canvas.SetTop(labelY, 200);
}
public void MouseChanged(int x, int y)
{
labelX.Content = "X=" + x.ToString();
labelY.Content = "Y=" + y.ToString();
}
}
提前致谢。