NotifyCollectionChangedEventHandler未与后台工作程序

时间:2016-06-07 08:10:39

标签: c# wpf inkcanvas

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控件未显示已加载的数据。为什么?当我们尝试没有后台工作人员,然后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>

1 个答案:

答案 0 :(得分:1)

您没有修改集合,而是要替换它。由于你的后台工作完成事件应该在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)
{