简体   繁体   English

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

[英]How to dynamically change the colour of label? Xamarin

I got this code below but I can't figure out how to make the selected label be turned into blue background colour and white text instead of what it has in unselected mode. 我在下面获得了此代码,但是我无法弄清楚如何使所选标签变成蓝色背景颜色和白色文本,而不是如何使其处于未选中模式。 There can only be 1 journey selected at time, and the one that is selected needs to be modified. 一次只能选择1个旅程,而所选择的旅程则需要修改。 I figured I could use datatriggers or behaviours. 我认为我可以使用数据触发或行为。 I can figure out how to change the button in the command, but how would I change the other buttons? 我可以弄清楚如何在命令中更改按钮,但是如何更改其他按钮? that gets unselected into gray? 变成未选中的灰色?

<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>

You just need to add a Selected property to your JourneyItems model and then even a BackgroundColor. 您只需将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;
}

Then bind the BackgroundColor and TextColor to change to color X when Selected is true and color Y otherwise. 然后,当Selectedtrue时,将BackgroundColorTextColor绑定为颜色X,否则为Y。

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

Finally, in ViewModel.SwitchJourneyCommand set your selected model to true and all other models to false . 最后,在ViewModel.SwitchJourneyCommand中将所选模型设置为true并将所有其他模型设置为false

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM