簡體   English   中英

從DispatcherTimer.Tick添加時,C#ListBox不顯示添加的項目

[英]C# ListBox not showing added items when added from DispatcherTimer.Tick

這對我來說似乎是一種怪異的行為,並且由於我不想怪自己以外的任何人,所以我花了數小時試圖解決這個問題-但我一點也不明白:

我只是注意到問題發生在DispatcherTimer.Tick事件調用的方法中。 這可能是一個多線程問題。

  1. 我有一個列表框:

     <ListBox ItemsSource="{Binding ConfigurationErrors, Mode=OneWay}"/> 
  2. 它綁定到:

     private ObservableCollection<string> _configurationErrors = new ObservableCollection<string>(); public ObservableCollection<string> ConfigurationErrors { get { return _configurationErrors; } } /// <summary> /// Adds a configuration error to the window. /// </summary> /// <param name="ErrorMessage">The message to add.</param> public void AddConfigurationError(string ErrorMessage) { if(String.IsNullOrEmpty(ErrorMessage)) return; _configurationErrors.Add(ErrorMessage); NotifyPropertyChanged("ConfigurationErrors"); } /// <summary> /// Removes all configuration errors from the window. /// </summary> public void ClearConfigurationErrors() { _configurationErrors.Clear(); NotifyPropertyChanged("ConfigurationErrors"); } 

AddConfigurationError(string ErrorMessage)成功添加一條消息,如果該消息被調用
MainWindow任何位置
(從構造函數和其他任何地方)

  1. 而且我在App.cs存儲的實例中也有一個不斷循環的方法(由DispatcherTimer.Tick調用),其中包含以下代碼:

      //File exists if (configFilePath == null) { _mainWindow.AddConfigurationError("Could not retrieve the config filepath."); throw new InvalidDataException("Could not retrieve the config filepath."); } else if (!File.Exists(configFilePath)) { _mainWindow.AddConfigurationError("Could not find the config. (" + configFilePath + ")"); throw new InvalidDataException("Could not find the config. (" + configFilePath + ")"); } 

引發異常,並調用AddConfigurationError() 我還可以記錄傳遞給AddConfigurationError()的消息,它確實有效,但是-我的控件未收到綁定更新。

這是因為DispatcherTimer.Tick在另一個線程中運行,並且綁定可能無法按我編寫它的方式正常工作嗎? 我該如何解決?

先感謝您。

在適當的MainWindow實例上調用方法。 您尚未顯示如何創建_mainWindow ,而是調用了

_mainWindow.AddConfigurationError(...);

你應該打電話

((MainWindow)Application.Current.MainWindow).AddConfigurationError(...);

這對我有用。 我使用MVVM,但我認為它應該可以在后面的代碼中工作

    public MainViewModel()
    {
        timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromSeconds(3);
        timer.Tick +=timer_Tick;
        timer.Start();
    }

    void timer_Tick(object sender, EventArgs e)
    {
        AddConfigurationError("err"); 
    }

XAML代碼

    <ListBox  ItemsSource="{Binding ConfigurationErrors}">

    </ListBox>

您無法從另一個線程訪問UI層,您需要執行以下操作

yourList.Invoke((MethodInvoker)(() =>
{
    //add new items here
}));

除了“ yourList”,您還可以使用主窗體或在主線程上運行的東西

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM