2016-06-07 51 views
-2

NotifyCollectionChangedEventHandler命令workling不與背景worker.Event工作是:NotifyCollectionChangedEventHandler沒有與後臺工作

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); 

我們正在結合斯托克在背景工作者完成事件的彙集。如下

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> 
+0

跨線程操作是不允許的。我想這是問題。 –

+0

您需要使用Dispatcher.Invoke在UI線程上運行代碼。 –

+0

你能提供確切的解決方案如何調用Dispatcher.Invoke – naina

回答

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) 
{