2017-01-23 44 views
1

我的Xamarin.Forms項目中有一個特定的屏幕。在XAML文件中,我創建了一個Slider元素,在後面的代碼中,我訪問滑塊以更新其值,但UI永遠不會在iOS上更改。在Android上完美運行。下面是相關的代碼:Xamarin.Forms - 在iOS中屬性分配不更新的滑塊,適用於Android

XAML

<?xml version="1.0" encoding="UTF-8"?> 
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="TnpApp.Forms.AudioPlayer" BackgroundColor="Gray"> 
    <ContentPage.Content> 
     <StackLayout Orientation="Vertical" Padding="16" > 
      // ... 
      <Slider x:Name="ProgressSlider" Minimum="0" Maximum="100"/> 
      // ... 
     </StackLayout> 
    </ContentPage.Content> 
</ContentPage> 

代碼背後

void UpdateCTI(object sender, ElapsedEventArgs e) 
{ 
    var progress = DependencyService.Get<IAudioPlayer>().GetAudioProgress(); 
    ProgressSlider.Value = progress; 
} 

我已經證實,(一個被調用在指定的時間間隔來更新UI法)這個方法每秒調用一次,並且progress變量中的值是正確的。從ProgressSlider.Value(用Console.WriteLine()確定)返回的值更新爲1,progress更新爲1,但在此之後不更改,即使progress繼續按預期增長。

同樣,這個問題只在iOS上,一切都在Android上完美運行。

誰能幫助我在這裏?

+2

如果UpdateCTI正在通過螺紋計時器則該函數在輔助線程正在執行執行時,使用Device.BeginInvokeOnMainThread – Gusman

+0

@Gusman謝謝,它修復了它!發佈這個答案,我會接受它。奇怪的是,它仍然在Android上工作... – Jonathan

回答

2

如果您的代碼正在線程計時器上執行,則該代碼正在輔助線程上執行,並且無法訪問UI。

要運行在主線程使用Device.BeginInvokeOnMainThread的代碼:

void UpdateCTI(object sender, ElapsedEventArgs e) 
{ 
    var progress = DependencyService.Get<IAudioPlayer>().GetAudioProgress(); 
    Device.BeginInvokeOnMainThread (() => ProgressSlider.Value = progress); 
} 
+0

這裏有詳細的鏈接:https://developer.xamarin.com/guides/xamarin-forms/platform-features/device/#Device.BeginInvokeOnMainThread – Jonathan

相關問題