【发布时间】:2020-07-10 22:33:18
【问题描述】:
我是 Xamarin.Forms 的新手,我正在开发我的第一个应用程序(适用于 Android 和 IoS)。
我有一组信息要显示在 ListView 内的网格布局中(数据源在后面的代码中设置)。
我必须根据源数据中的一些值更改框架的颜色和相关标签的文本。
这是工作代码(使用占位符作为框架颜色和标签文本):
XAML:
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid x:Name="GridLayout" Padding="20">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Label Text="{Binding Name}" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" FontSize="18" TextColor="Black" FontAttributes="Bold" />
<Label Text="{Binding LessonDate}" Grid.Row="1" Grid.Column="0" FontSize="14" TextColor="Gray" />
<Label Text="{Binding StartEndTime}" Grid.Row="1" Grid.Column="1" FontSize="14" TextColor="Gray" Margin="-30,0,0,0"/>
<Frame Grid.Row="2" Grid.Column="0"
CornerRadius="15"
Padding="0"
BackgroundColor="Silver"
Margin="0,10,0,10"
HasShadow="False"
WidthRequest="125"
x:Name="UserStatusFrame">
<Label Text="Placeholder" Margin="5" HorizontalOptions="Center" BackgroundColor="Transparent"
TextColor="Gray" x:Name="UserStatusLabel"/>
</Frame>
<Frame Grid.Row="2" Grid.Column="1"
CornerRadius="15"
Padding="0"
BackgroundColor="Yellow"
Margin="0,10,0,10"
HasShadow="False"
WidthRequest="125"
x:Name="CourseStatusFrame">
<Label Text="Placeholder" Margin="5" HorizontalOptions="Center" BackgroundColor="Transparent"
TextColor="Black" x:Name="CourseStatusLabel" />
</Frame>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
代码背后:
protected override void OnAppearing()
{
base.OnAppearing();
FillUncompletedLessonsList(); // fills the list from a rest WS using a simple model class
LessonsListview.ItemsSource = UncompletedLessonsList;
SetListViewFormat();
}
我想做的是创建一个函数 SetListViewFormat,我可以在其中根据某些数据标准从后面的代码中管理标签文本和框架颜色。
例如,类似:
foreach item in the list {
if UncompletedLessonsList.completed == true {
UserStatusLabel.Text = "Completed"
UserStatusFrame.BackgroundColor = "Green"
}
}
但我不明白我可以通过哪种方式动态访问这些设置..
提前感谢您的帮助!
编辑 1 - 数据模型:
UncompletedLessonsList 是一个课程列表
public class Lesson
{
public string Name { get; set; }
public string Description { get; set; }
public string LessonDate { get; set; }
public string StartEndTime { get; set; }
public string Location { get; set; }
public string State { get; set; }
public bool Completed { get; set; }
public RestWSTeacher Teacher { get; set; }
public List<Activity> Activities { get; set; }
}
【问题讨论】:
-
您需要使用数据绑定和值转换器来完成此操作
-
你能发布你的UncompletedLessonsList的数据模型吗?
-
你能发布你的UncompletedLessonsList的数据模型吗?
-
嗨 AndroDevil,我在问题中添加了它。谢谢
-
嗨@Jason .. 您建议的方法与Jack Hua 建议的方法相同吗?我在问我是否可以在不使用 mvvm 模式的情况下使用这种方法,以及它是否可以用于各种转换:我必须更改用户状态框架颜色和基于布尔已完成的标签,我必须更改另一个标签和另一个基于作为字符串的状态属性的框架..我怎样才能实现这些目标?谢谢
标签: xamarin.forms cross-platform xamarin.forms.listview