以下是View的一部分,其中已将图像绑定(bind)到ViewModel中的属性:

<Image Source="{Binding Image}"  Grid.Column="2" Grid.ColumnSpan="2"/>

我的ViewModel是这样的:
public class MainWindowViewModel : INotifyPropertyChanged
{
    public BitmapImage Image
    {
        get { return _image; }
        set
        {
            _image = value;
            OnPropertyChanged();
        }
    }

    Action _makeScannerAlwaysOnAction;
    private BitmapImage _image;


    public MainWindowViewModel()
    {
        AddNewPersonCommand = new RelayCommand(OpenFrmAddNewPerson);
        FingerPrintScannerDevice.FingerPrintScanner.Init();
        MakeScannerAlwaysOn(null);
    }

    private void MakeScannerAlwaysOn(object obj)
    {
        _makeScannerAlwaysOnAction = MakeScannerOn;
        _makeScannerAlwaysOnAction.BeginInvoke(Callback, null);
    }

    private void Callback(IAsyncResult ar)
    {
        FingerPrintScannerDevice.FingerPrintScanner.UnInit();
        var objFingerPrintVerifier = new FingerPrintVerifier();
        objFingerPrintVerifier.StartVerifingProcess();
        var ms = new MemoryStream();
        ms.Position = 0;
        objFingerPrintVerifier.MatchPerson.Picture.Save(ms, ImageFormat.Png);
        var bi = new BitmapImage();
        bi.BeginInit();
        bi.StreamSource = ms;
        bi.EndInit();
        Thread.Sleep(2000);
        Dispatcher.CurrentDispatcher.Invoke(() => Image = bi);
        //Image = bi;

        _makeScannerAlwaysOnAction.BeginInvoke(Callback, null);
    }

    private void MakeScannerOn()
    {
        while (true)
        {
            if (FingerPrintScannerDevice.FingerPrintScanner.ScannerManager.Scanners[0].IsFingerOn)
            {
                return;
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

我的问题:
问题是当我想绑定(bind)图像时,它给了我错误



我在Google上搜索了很多东西,并且看到过SO的帖子,但是他们都不适合我。

任何帮助将不胜感激。

最佳答案

BitmapImageDependencyObject,所以它在哪个线程上创建都没有关系,因为您不能访问在另一个线程上创建的对象的DependencyProperty,除非它是 Freezable 对象并且可以对其进行 Freeze



您需要做的是在更新Freeze之前调用Image:

bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();
bi.Freeze();

Dispatcher.CurrentDispatcher.Invoke(() => Image = bi);

正如@AwkwardCoder指出的,这里是Freezable Objects Overview

关于c# - 错误: Must create DependencySource on same Thread as the DependencyObject even by using Dispatcher,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26361020/

10-08 22:31