【问题标题】:NotifyCollectionChangedEventHandler is not workling with background workerNotifyCollectionChangedEventHandler 不与后台工作人员一起使用
【发布时间】:2016-06-07 08:10:39
【问题描述】:

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

我们正在后台工作人员完成事件上绑定 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>

【问题讨论】:

  • 不允许跨线程操作。我想这就是问题所在。
  • 您需要使用 Dispatcher.Invoke 在 UI 线程上运行代码。
  • 您能否提供确切的解决方案如何通过 Dispatcher.Invoke 调用
  • @Patrick Hofman 没有显示任何错误
  • @PatrickHofman 不应该是跨线程的,OP 说它是在完成的事件代码上触发的,应该编组回 UI 线程。

标签: c# wpf inkcanvas


【解决方案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)
{

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多