将Xamarin XAML绑定到属性后面的代码(ListView)

时间:2018-08-24 15:34:46

标签: xamarin data-binding properties code-behind

我想将我的代码隐藏属性(即列表)绑定到XAML ListView。但是,我的ListView从来没有被填充,我也不知道为什么。

<?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="BLEPl.EvaluationPage"
             Title="Evaluation">
    <ContentPage.Content>
        <StackLayout Padding="0,20,0,20">      
            <ListView HasUnevenRows="True" IsVisible="True" x:Name="TableLayout" ItemsSource="{Binding Path=SensorValues}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Grid>
                                <Label Style="{StaticResource TitleLabel}" Grid.Column="0" Grid.Row="0" Text="Zeitstempel: " />
                                <Label Style="{StaticResource DataLabel}" Grid.Column="1" Grid.Row="0" Text="{Binding TimeStamp}" />

                                <Label Style="{StaticResource TitleLabel}" Grid.Column="0" Grid.Row="1" Text="Wert: " />
                                <Label Style="{StaticResource DataLabel}" Grid.Column="1" Grid.Row="1" Text="{Binding Value}" />

                                <Label Style="{StaticResource TitleLabel}" Grid.Column="0" Grid.Row="2" Text="Sensor: " />
                                <Label Style="{StaticResource DataLabel}" Grid.Column="1" Grid.Row="2" Text="{Binding Sensor.Name}" />
                            </Grid>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class EvaluationPage : ContentPage
{
    private ObservableCollection<SensorValue> SensorValues = new ObservableCollection<SensorValue>();

    public EvaluationPage ()
    {
        InitializeComponent ();

        using (var context = new BlepContext(true))
        {
            var repo = new BLEPRepository(context);
            SensorValues = new ObservableCollection<SensorValue>(repo.GetAllSensorValues());
        }
    }
}

运行此命令时,我的ListView不包含任何项目。我没有收到错误,我的应用程序可以正常编译。我在这里做错什么了吗?

1 个答案:

答案 0 :(得分:0)

<ListView HasUnevenRows="True" IsVisible="True" x:Name="TableLayout" ItemsSource="{Binding SensorValues}">

您只能绑定到公共属性,并且需要为页面设置BindingContext

// needs to be a PUBLIC PROPERTY
public ObservableCollection<SensorValue> SensorValues { get; set; }

public EvaluationPage ()
{
    InitializeComponent ();

    // set the BindingContext
    this.BindingContext = this;

    using (var context = new BlepContext(true))
    {
        var repo = new BLEPRepository(context);
        SensorValues = new ObservableCollection<SensorValue>(repo.GetAllSensorValues());
    }
}