gpt4 book ai didi

c# - 错误 : Must create DependencySource on same Thread as the DependencyObject even by using Dispatcher

转载 作者:IT王子 更新时间:2023-10-29 04:22:50 29 4
gpt4 key购买 nike

以下是我的 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)图像时它给了我错误

Must create DependencySource on same Thread as the DependencyObject

我用谷歌搜索了很多,我在 SO 中看到了这篇文章,但它们都不适合我。

我们将不胜感激任何形式的帮助。

最佳答案

BitmapImageDependencyObject 因此它在哪个线程上创建很重要,因为您无法访问在另一个线程上创建的对象的 DependencyProperty除非它是 Freezable对象,你可以 Freeze它。

Makes the current object unmodifiable and sets its IsFrozen property to true.

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

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com