Xamarin中点击自定义Tab时如何修改属性设置选中激活状态
你的现有代码存在两个问题:
tabactive是点击事件内的局部变量,ActiveColorBg方法无法读取该值- 没有对指示Label的背景色进行赋值操作,所以修改不生效
步骤1:修改XAML,给指示条添加唯一标识
给每个Tab下方的指示Label添加x:Name属性,方便后台代码访问:
<StackLayout Padding="10,10,10,0"> <Frame x:Name="tab1" Padding="0" HasShadow="False"> <StackLayout> <Label TextColor="#848484" FontSize="13" HorizontalTextAlignment="Center" Text="Tab 1" /> <!-- 给指示条添加x:Name --> <Label x:Name="tab1Indicator" HeightRequest="2" Margin="0,3,0,0" HorizontalOptions="FillAndExpand" BackgroundColor="#00AA13" /> </StackLayout> <Frame.GestureRecognizers> <TapGestureRecognizer Tapped="tab1_Tapped" /> </Frame.GestureRecognizers> </Frame> </StackLayout> <StackLayout Padding="10,10,10,0"> <Frame x:Name="tab2" Padding="0" HasShadow="False"> <StackLayout> <Label TextColor="#848484" FontSize="13" HorizontalTextAlignment="Center" Text="Tab 2" /> <!-- 给指示条添加x:Name --> <Label x:Name="tab2Indicator" HeightRequest="2" Margin="0,3,0,0" HorizontalOptions="FillAndExpand" BackgroundColor="#fff" /> </StackLayout> <Frame.GestureRecognizers> <TapGestureRecognizer Tapped="tab2_Tapped" /> </Frame.GestureRecognizers> </Frame> </StackLayout>
步骤2:修改后台逻辑
// 类内定义全局变量,存储当前激活Tab标识和颜色配置 private string _activeTab = "tab1"; // 默认第一个Tab激活 private const string ActiveBgColor = "#00AA13"; private const string DefaultBgColor = "#fff"; private void tab1_Tapped(object sender, EventArgs e) { _activeTab = "tab1"; ActiveColorBg(); } private void tab2_Tapped(object sender, EventArgs e) { _activeTab = "tab2"; ActiveColorBg(); } private void ActiveColorBg() { // 先重置所有Tab的指示条为默认颜色 tab1Indicator.BackgroundColor = Color.FromArgb(DefaultBgColor); tab2Indicator.BackgroundColor = Color.FromArgb(DefaultBgColor); // 给当前激活的Tab设置高亮色 switch(_activeTab) { case "tab1": tab1Indicator.BackgroundColor = Color.FromArgb(ActiveBgColor); // 此处可添加Tab1对应的内容区域切换逻辑 break; case "tab2": tab2Indicator.BackgroundColor = Color.FromArgb(ActiveBgColor); // 此处可添加Tab2对应的内容区域切换逻辑 break; } }
优化方案(可选)
如果Tab数量较多,可复用同一个点击事件减少重复代码:
- 修改XAML中TapGestureRecognizer的配置,添加CommandParameter传参:
<!-- Tab1配置 --> <TapGestureRecognizer Tapped="Tab_Tapped" CommandParameter="tab1" /> <!-- Tab2配置 --> <TapGestureRecognizer Tapped="Tab_Tapped" CommandParameter="tab2" />
- 后台仅保留一个统一的点击事件:
private void Tab_Tapped(object sender, EventArgs e) { var tapRecognizer = sender as TapGestureRecognizer; _activeTab = tapRecognizer.CommandParameter.ToString(); ActiveColorBg(); }
内容的提问来源于stack exchange,提问作者Chim Di Tru
相关产品推荐
相关产品推荐

