【问题标题】:Cannot access TextBlock properties in Windows Phone 8无法访问 Windows Phone 8 中的 TextBlock 属性
【发布时间】:2015-02-04 13:50:48
【问题描述】:

我正在通过蓝牙从外部设备接收一些数据,并且我有一个事件处理程序,它会在收到数据时触发。这是一个非常基本的应用程序,我在主页上有一个按钮,按下该按钮时会执行以下功能:

async void BLE_Function()
    {
        //some code to connect to the device

        thermometerCharacteristic.ValueChanged += temperatureMeasurementChanged; //this is where I had a function to the event handler

        await thermometerCharacteristic
            .WriteClientCharacteristicConfigurationDescriptorAsync(
                GattClientCharacteristicConfigurationDescriptorValue.Notify);
    }    

public void temperatureMeasurementChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
    {
        //Store the incoming bytes in a byte array called "temperatureData"

        foreach (byte b in temperatureData)
        {
            Debug.WriteLine(b.ToString());
        }
    }    

现在的问题是我想在一个简单的 TextBlock 中显示接收到的字节,它也在 MainPage 上,就像上面的代码一样,但是当我写 MyTextBlock.Text = b.ToString()foreach 循环中,Visual Studio 引发访问冲突异常。我在 BLE_Function() 中使用了相同的 TextBlock,并且在那里它工作正常,所以我不明白为什么我不能从 temperatureMeasurementChanged 函数访问它。下面粘贴的是异常详细信息:

System.UnauthorizedAccessException 未被用户代码处理
HResult=-2147024891
Message=无效的跨线程访问。
源=System.Windows
堆栈跟踪: 在 MS.Internal.XcpImports.CheckThread() 在 System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp,对象值,布尔值 allowReadOnlySet) 在 System.Windows.Controls.TextBlock.set_Text(字符串值) 在 PhoneApp2.MainPage.displayText(字节数据) 在 PhoneApp2.MainPage.temperatureMeasurementChanged(GattCharacteristic 发件人,GattValueChangedEventArgs 参数)
内部异常:

提前致谢。

【问题讨论】:

    标签: c# visual-studio windows-phone-8


    【解决方案1】:

    引发异常是因为您尝试从 GUI 线程以外的另一个线程更新 GUI。您必须使用 Dispatcher.BeginInvoke() 来更新 GUI。你可以找到一个例子here

    【讨论】:

    • 谢谢,这行得通,但如果这是一个线程问题,我不明白我如何能够直接从异步 BLE_Function 而不是从偶数处理函数访问 TextBlock?
    • 那是因为 BLE_Function 在 GUI 线程上,而事件处理程序在单独的线程上,因为它是异步调用的。
    猜你喜欢
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多