如何动态更改标签的颜色? Xamarin

时间:2019-04-26 23:39:06

标签: c# xaml xamarin xamarin.forms

我在下面获得了这段代码,但是我无法弄清楚如何使所选标签变成蓝色背景颜色和白色文本,而不是如何使其处于未选中模式。一次只能选择1个旅程,而所选择的旅程则需要修改。我认为我可以使用数据触发或行为。我可以弄清楚如何在命令中更改按钮,但是如何更改其他按钮?变成未选中的灰色?

<CollectionView Grid.Row="1" Grid.Column="0" ItemsSource="{Binding JourneyItems}" SelectionMode="Single"  ItemsLayout="{x:Static ListItemsLayout.HorizontalList}">
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <StackLayout Orientation="Horizontal" >
                <StackLayout Margin="10,0,10,0" BackgroundColor="LightGray"  VerticalOptions="Fill"  Orientation="Horizontal" >
                    <Label Text="{Binding Name}"  TextColor="{StaticResource ThemeBkColor}" VerticalTextAlignment="Center" VerticalOptions="Center" />
                </StackLayout>

                <StackLayout.GestureRecognizers>
                    <TapGestureRecognizer Command="{Binding Path=ViewModel.SwitchJourneyCommand, Source={x:Reference ThisJourneysPage}}"
                        CommandParameter = "{Binding .}" NumberOfTapsRequired="1"/>
                </StackLayout.GestureRecognizers>
            </StackLayout>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

1 个答案:

答案 0 :(得分:2)

您只需要向Selected模型中添加JourneyItems属性,然后甚至为BackgroundColor。

public class JourneyItem {
    // more stuff

    public bool Selected { get; set; }

    public Color BackgroundColor => Selected ? Color.Blue : Color.Gray;

    public Color TextColor => Selected ? Color.White : Color.Black;
}

然后将BackgroundColorTextColor绑定为Selectedtrue时颜色X,否则为Y颜色。

<Label Text="{Binding Name}"  TextColor="{Binding TextColor}"  BackgroundColor="{Binding BackgroundColor}"/>

最后,在ViewModel.SwitchJourneyCommand中将所选模型设置为true,将所有其他模型设置为false

public void OnJourneyCommand(JourneyItem selectedItem) {
    foreach(JourneyItem item in JourneyItems) {
        item.Selected = item.Id == selectedItem.Id;
    }
}