我有一个CollectionView,里面有一个Frame, Frame的背景颜色会根据变量"GetColor"的字符串值而改变。从Database的每个对象中收集字符串数据,但是Frame的backgroundcolor仍然为"红色"。一直都是。
# CollectionView
<CollectionView Margin="5" ItemsSource="{Binding ListGroupData}"
ItemsUpdatingScrollMode="KeepLastItemInView" ItemTemplate="{StaticResource
GroupDataTemplateSelector}" VerticalOptions="FillAndExpand"
HorizontalOptions="FillAndExpand"/>
<ResourceDictionary>
<DataTemplate x:Key="RedTemplate">
<StackLayout>
<Frame HasShadow="False" Padding="10" HorizontalOptions="StartAndExpand"
BackgroundColor="Red"
CornerRadius="15">
<Label Text="{Binding Name}" TextColor="Black"/>
</Frame>
</StackLayout>
</DataTemplate>
<DataTemplate x:Key="GreenTemplate">
<StackLayout>
<Frame HasShadow="False" Padding="10" HorizontalOptions="EndAndExpand"
BackgroundColor="Green"
CornerRadius="15">
<Label Text="{Binding Name}" TextColor="Black"/>
</Frame>
</StackLayout>
</DataTemplate>
<Local:GroupDataViewModel x:Key="GroupDataTemplateSelector" RedTemplate="
{StaticResource
RedTemplate}" GreenTemplate="{StaticResource GreenTemplate}"/>
</ResourceDictionary>
# TemplateSelector代码protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
if (GetColor == "Red")
return RedTemplate;
else
return GreenTemplate;
}
public DataTemplate RedTemplate { get; set; }
public DataTemplate GreenTemplate { get; set; }
#公共变量public string GetColor;
public ObservableCollection<GroupData> ListGroupData = new ObservableCollection<GroupData>();
#支持代码FirebaseClient fc = new FirebaseClient("...");
var result = await fc.Child("GroupData").OnceAsync<GroupData>();
foreach (var item in result)
{
GetColor = item.Object.Color;
ListGroupData.Add(item.Object);
}
///this part the item that is being added to the ListGroupData(CollectionView) suppose to
have different backgroundcolor bases on its data
您不需要公共属性GetColor
。因为该属性会对集合中的每个对象求值,而不是在视图模型中求值。
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
//Your list is a list of GroupData. then you will need to cast item to the type of your object
var targetColor = (GroupData)item.Color;
if (targetColor == "Red") //this if the item.Color is String
return RedTemplate;
else
return GreenTemplate;
}
PD:
或者如果你的item.Color
是一个颜色类型,你可以在CollectionView.ItemTemplate
中使用它来为你的框架着色。你只需要给那个属性添加一个绑定。(你可以删除所有的TemplateSelector代码)
如果您的item.Color
不是颜色类型,您将不得不添加一个转换器(您将不得不对其进行编码),将值转换为颜色。
<CollectionView Margin="5"
ItemsSource="{Binding ListGroupData}"
ItemsUpdatingScrollMode="KeepLastItemInView"
VerticalOptions="FillAndExpand"
HorizontalOptions="FillAndExpand">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Frame HasShadow="False"
Padding="10"
HorizontalOptions="EndAndExpand"
BackgroundColor="{Binding Color}"
CornerRadius="15">
<Label Text="{Binding Name}" TextColor="Black"/>
</Frame>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>