2017-10-10 160 views
-1

我無法在屏幕上顯示新數據。Xamarin.Forms綁定不起作用

C#代碼

public partial class MainPage : ContentPage { 
    public class PhaseDetails { 
     public List<string> Chats { 
      get; set; 
     } 
    } 

    public new PhaseDetails BindingContext => (PhaseDetails) base.BindingContext; 

    public MainPage() { 
     InitializeComponent(); 
     base.BindingContext = new PhaseDetails { 
      Chats = new List<string>(new string[] { "qwe" }), 
     }; 
     Task.Run(() => new List<string>(new string[] { "1", "2", "3" })).ContinueWith((task) => Device.BeginInvokeOnMainThread(() => { 
      BindingContext.Chats = task.Result; 
      OnPropertyChanged(null); 
     })); 
    } 
} 

XAML

<StackLayout> 
    <ListView ItemsSource="{Binding Chats}"> 
     <ListView.ItemTemplate> 
      <DataTemplate> 
       <ViewCell> 
        <StackLayout Padding="6" BackgroundColor="Aquamarine"> 
         <Label Text="Service Area"/> 
        </StackLayout> 
       </ViewCell> 
      </DataTemplate> 
     </ListView.ItemTemplate> 
    </ListView> 
</StackLayout> 

預期:在列表視圖中三行。 但它只顯示一個。 可能是什麼問題?

+0

如果'task.Result'具有任何值,則問題是,你不會從變化通知視圖('OnPropertyChanged(NULL);')。你應該做'OnPropertyChanged(「聊天」);' –

+0

PhaseDetails不實現INPC。而且你似乎沒有從正確的上下文中調用PropertyChanged - 它通常在setter中。 – Jason

回答

0

這幫助:

 public class PhaseDetails { 
... 
      public event PropertyChangedEventHandler PropertyChanged; 
      void OnPropertyChanged([CallerMemberName] string propertyName = null) { 
       PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 
      } 

呼叫從屬性setter OnPropertyChanged。

1

你可以嘗試這個github頁面上可用的simple project solution。它使用從ViewModel到View的數據綁定模式= TwoWay。

enter image description here