【问题标题】:WPF retrieve leap info from different classWPF 从不同的类中检索跳跃信息
【发布时间】:2015-02-25 15:55:37
【问题描述】:

我的问题的快速版本是 WPF 不接受来自不同线程的变量。

error message: 
An unhandled exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll

附加信息:调用线程无法访问此对象,因为不同的线程拥有它。

因为我订阅了闰帧事件,我找不到第二个线程的解决方法。以下代码中是否有某种方法可以将框架信息放入文本框中?

// MainWindow
LeapReader reader = new LeapReader();
public MainWindow()
{
    reader.Frame += reader_Frame;
}

void reader_Frame(string coordinate)
{
    //textbox which will output coordinates of the hand
    txtCoord.Text = coord;
}


// LeapReader
string _coordinates = "";
public delegate void StringEvent(string coord);
public event StringEvent Frame;

void SomeRetrievalMethod(Frame frame)
{
    _coordinates = Cursor.Position.ToString();
    Frame.Invoke(_coordinates);
}

【问题讨论】:

    标签: c# wpf multithreading leap-motion


    【解决方案1】:

    将其发送回TextBox's Dispatcher。如果您只使用绑定并让WPF 为您处理线程之间的调度会更好。

    void reader_Frame(string coordinate)
    {
        //textbox which will output coordinates of the hand
        txtCoord.Dispatcher.Invoke(new Action(() => txtCoord.Text = coord));
    } 
    

    【讨论】:

    • 这是一个很好的资源,可以帮助您了解 Dispatcher 到底是什么。 link
    • @MikeEason 那篇文章太旧了。如果您使用的是 .NET 4.5 >。在 TPL 中使用 async/await 比使用 BackgroundWorkers 更好。并使用Rx 获得更好的响应式应用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多