2017-10-10 108 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