Xamarin.Forms绑定不起作用

时间:2017-10-10 16:09:46

标签: data-binding 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>

预期:列表视图中有三行。 但它只显示一个。 可能是什么问题?

2 个答案:

答案 0 :(得分:1)

您可以在此github页面上尝试此simple project solution。它使用从ViewModel到View的数据绑定模式= TwoWay。

enter image description here

答案 1 :(得分:0)

这有助于:

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

从属性设置器调用OnPropertyChanged。