Xamarin:将类对象属性绑定到ListView文本

时间:2018-04-10 23:58:58

标签: c# listview xamarin

我有一个对象列表List<Shift> ListOfShift = new List<Shift>();,我想在Xamarin中创建ListView,在单元格中显示Shift对象的第一个值。

这是我的Shift类的代码:

public String StringShift { get; set; }
DateTime StartOfShift { get; set; }
DateTime EndOfShift { get; set; }


    public Shift(DateTime StartShift, DateTime EndShift)
    {
        StartOfShift = StartShift;
        EndOfShift = EndShift;

        StringShift = Convert.ToString(StartOfShift);
    }

    public string StringShow()
    {
        string ShiftText = Convert.ToString(StartOfShift) + " " + Convert.ToString(EndOfShift);
        return ShiftText;
    }

以下是XAML:

<ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <Label Text="{Binding .}" />
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>

我尝试了以下内容:

<Label Text="{Binding .}" />
<Label Text="{Binding Shift.StartOfShift}" /> // Prints blank
<Label Text="{Binding Shift.StringShift}" /> // Prints blank

如何将Text值设为目标对象属性?

注意:

List确实有效,并且正在使用正确的值添加项目,我可以按预期使用列表对象,我只想让它们显示。

编辑:

完整的XAML代码

<Grid>

<Grid.ColumnDefinitions>
    <ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>       
<Grid.RowDefinitions>
    <RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button
    x:Name="ShiftAdd"
    Clicked="AddButton"
    Text="Add"
    Grid.Column="0"
    Grid.ColumnSpan="2"
    Grid.Row="2"
/>
<ListView 
    x:Name="ShiftListViewer"
    BackgroundColor="AntiqueWhite"
    SeparatorColor="Black"
    Grid.Column="0"
    Grid.ColumnSpan="4"
    Grid.Row="0"
    Grid.RowSpan="2">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
    <Label Text="{Binding Shift.ShiftOfStart}" />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</ContentPage>

C#代码:

//Within a button event

DateTime Shift1 = new DateTime(2018,1,1,10,0,0);
DateTime Shift2 = new DateTime(2018,1,1,19,0,0);
New List<Shift> ListOfShifts = new List<Shift>();
ListOfShifts.Add(new Shift(Shift1, Shift2));

ShiftListViewer.ItemsSource = ListOfShifts;
    ShiftListViewer.BindingContext = "Shift.StartOfShift";

1 个答案:

答案 0 :(得分:0)

如果ItemsSourceList<Shift>,则ListView中的每个元素都属于Shift类型。这意味着绑定表达式将相对于Shift

// tries to display Shift object
<Label Text="{Binding .}" />
// won't work, there is no "Shift" property on the Shift object
<Label Text="{Binding Shift.StartOfShift}" /> 
// won't work, there is no "Shift" property on the Shift object
<Label Text="{Binding Shift.StringShift}" /> 

// this should work, "StringShift" is a public property of Shift
<Label Text="{Binding StringShift}" />