桌面警报在子方法中不起作用

时间:2015-03-13 16:29:15

标签: c# wpf

我正在使用Ivan Leonenko的“Growl Alike WPF Notifications”(@ codeproject.com)。

这在我在MainWindow中添加通知时有效 当我在子方法中添加通知时,警报不会出现
这是我的工作代码:

    private User user;
    private readonly GrowlNotifiactions growlNotifications = new GrowlNotifiactions();

    public MainWindow()
    {
        InitializeComponent();

        // Sample output GrowlNotification works
        addAlertDesktop("Hello #1", "Lorem Ipsum");
        addAlertDesktop("Hello #2", "Lorem Ipsum");
        addAlertDesktop("Hello #3", "Lorem Ipsum");
    }

    private void addAlertDesktop(string title, string message)
    {
        growlNotifications.AddNotification(new Notification { Title = title, ImageUrl = "pack://application:,,,/Resources/notification-icon.png", Message = message });
    }

这是不起作用的代码:

    private User user;
    private readonly GrowlNotifiactions growlNotifications = new GrowlNotifiactions();

    public MainWindow()
    {
        InitializeComponent();
    }

    private void addAlertDesktop(string title, string message)
    {
        growlNotifications.AddNotification(new Notification { Title = title, ImageUrl = "pack://application:,,,/Resources/notification-icon.png", Message = message });
    }

    private void setTimer(User user) {
        Timer timer = new Timer(5000);
        systemTimer.Elapsed += (sender, e) => OnTimerElapsed(user);
        systemTimer.AutoReset = true;
        systemTimer.Enabled = true;
    }

    private void OnTimerElapsed(User user)
    {
        checkUser(user);
    }

    private void myButton_Click(object sender, RoutedEventArgs e) {
        User currentUser = (User)sender;
        checkUser(user);
    }

    private void checkUser(User user)  {
        setTimer(user);
        addAlertDesktop("Hello #1", "Lorem Ipsum");
        user.checked = 1;
    }

1 个答案:

答案 0 :(得分:1)

如果是您尝试从后台线程更新UI的问题;尝试用DispatcherTimer替换你的计时器:

DispatcherTimer timer = new DispatcherTimer();
timer.Interval = 5000;
timer.Tick += (sender, e) => OnTimerElapsed(user);
timer.Start();

如果您想继续使用Timer类,您仍然可以将后续代码封送到调度程序:

将addAlertDesktop更改为:

Application.Current.Dispatcher.Invoke(() = > growlNotifications.AddNotification(new Notification { Title = title, ImageUrl = "pack://application:,,,/Resources/notification-icon.png", Message = message }));