如何在使用TabItemSource时为TabView设置TextColorSelected属性
解决方案
当你通过TabItemsSource配合自定义TabViewItemDataTemplate渲染标签项时,XCT原生的TextColorSelected属性是针对默认TabViewItem样式生效的,自定义模板后需要自行控制选中态的文字颜色,这里提供两种最常用的实现方案:
方案1:使用VisualStateManager(推荐,无需修改ViewModel)
直接在你的自定义Tab项模板里添加选中状态的视觉管理,修改你的xct:TabView.TabViewItemDataTemplate部分代码如下:
<xct:TabView.TabViewItemDataTemplate> <DataTemplate> <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="CenterAndExpand"> <VisualStateManager.VisualStateGroups> <VisualStateGroup Name="CommonStates"> <VisualState Name="Normal"> <VisualState.Setters> <Setter Property="Label.TextColor" Value="Black" TargetName="TabLabel"/> </VisualState.Setters> </VisualState> <VisualState Name="Selected"> <VisualState.Setters> <!-- 这里设置你需要的选中态文字颜色,可自行修改 --> <Setter Property="Label.TextColor" Value="Red" TargetName="TabLabel"/> </VisualState.Setters> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Label x:Name="TabLabel" Text="{Binding Location}" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" FontAttributes="Bold"/> </StackLayout> </DataTemplate> </xct:TabView.TabViewItemDataTemplate>
XCT的TabView会自动为当前选中的Tab项触发Selected视觉状态,无需额外编写业务逻辑即可自动切换文字颜色。
方案2:绑定ViewModel选中状态
如果你的业务逻辑本身需要记录选中的Tab项,也可以通过数据绑定实现:
- 给你的
KitchenOrder模型类添加IsSelected布尔属性,需要实现INotifyPropertyChanged接口通知属性变更 - 在ViewModel中监听
SelectedIdx属性的变更,遍历KitchenOrderCollection更新对应下标的项的IsSelected值 - 实现布尔值转颜色的IValueConverter,将Label的TextColor绑定到
IsSelected属性配合转换器切换颜色即可
内容的提问来源于stack exchange,提问作者Ooi Yoong Khang
相关产品推荐
相关产品推荐

