Cannot access non-static method in static context?

前端 未结 3 2026
春和景丽
春和景丽 2021-02-04 17:02

Given this code....

public class CalibrationViewModel : ViewModelBase
{
    private FileSystemWatcher fsw;

    public CalibrationViewModel(Calibration calibrati         


        
相关标签:
3条回答
  • 2021-02-04 17:25

    It's because Dispatcher is a class not a property. Shouldn't you be making your CalibrationViewModel class a subclass of some other class which has a Dispatcher property?

    0 讨论(0)
  • 2021-02-04 17:31

    Change this:

    Dispatcher.BeginInvoke
    

    to this:

    Dispatcher.CurrentDispatcher.BeginInvoke
    

    the issue is BeginInvoke is an instance method and needs an instance to access it. However, your current syntax is trying to access BeginInvoke in a static manner off the class Dispatcher and that's what's causing this error:

    Cannot access non-static method BeginInvoke in static context

    0 讨论(0)
  • 2021-02-04 17:41

    If this is WPF, System.Windows.Threading.Dispatcher does not have a static BeginInvoke() method.

    If you want to call that statically (this is, without having a reference to the Dispatcher instance itself), you may use the static Dispatcher.CurrentDispatcher property:

    Dispatcher.CurrentDispatcher.BeginInvoke(...etc);
    

    Be aware though, that doing this from a background thread will NOT return a reference to the "UI Thread"'s Dispatcher, but instead create a NEW Dispatcher instance associated with the said Background Thread.

    A more secure way to access the "UI Thread"'s Dispatcher is via the use of the System.Windows.Application.Current static property:

    Application.Current.Dispatcher.BeginInvoke(...etc);
    
    0 讨论(0)
提交回复
热议问题