NotifyCollectionChangedEventHandler 不与后台工作者一起工作

NotifyCollectionChangedEventHandler is not workling with background worker

NotifyCollectionChangedEventHandler 命令不适用于后台 worker.Event 如下:

void MainWindowsViewModel_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    StrokesEllipse = ((StrokeCollection)sender);
    using (var memoryStream = new MemoryStream())
    {
        StrokesEllipse.Save(memoryStream);
        //convert memory stream to  array
        EllipseDrawing = memoryStream.ToArray();
        //save the above array to say - database
        }
    }

我们在构造函数上声明了如下事件

_strokesEllipse = new StrokeCollection();
(_strokesEllipse as INotifyCollectionChanged).CollectionChanged += new NotifyCollectionChangedEventHandler(MainWindowsViewModel_CollectionChanged);

我们正在后台工作人员完成事件上绑定 stoke 集合。如下

string s = GetMechanicSignature();
if (s != "")
{
    EllipseDrawing = Convert.FromBase64String(s);
}
if (EllipseDrawing != null)
{
    try
    {
        using (var memoryStream = new MemoryStream(EllipseDrawing))
        {
            _strokesEllipse = new StrokeCollection(memoryStream);
        }
    }
    catch (Exception)
    {

}

inkcanvas 控件不显示加载的数据。为什么?当我们尝试不使用后台 worker 时,inkcanvas 能很好地控制加载数据吗? inkcanvas xml 如下

<InkCanvas x:Name="inkCanVas" Grid.Row="0" IsEnabled="{Binding VCRSignatureModel.IsEnable,Mode=TwoWay}" Background="White"  Width="700" Height="90" Margin="40,0,0,0" Strokes="{Binding StrokesEllipse,Mode=TwoWay}">
    <InkCanvas.DefaultDrawingAttributes>
        <DrawingAttributes Color = "Black" Width = "6" />
    </InkCanvas.DefaultDrawingAttributes>
</InkCanvas>

您不是在修改 collection,您是在替换它。由于您的后台工作完成事件应该在 UI 线程中触发,所以这不是线程问题。

解决此问题的最快方法是在工作人员完成的代码中的 _strokesEllipse = new StrokeCollection(memoryStream); 行之后添加以下行。

MainWindowsViewModel_CollectionChanged(
   _strokesEllipse,
   new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace);

或者您可以将代码更改为:

try
{
    using (var memoryStream = new MemoryStream(EllipseDrawing))
    {
        var newCollection = new StrokeCollection(memoryStream);
        _strokesEllipse.Clear();
        _strokesEllipse.Add(newCollection);
    }
}
catch (Exception)
{