You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MAUI中如何根据IsCd绑定值在CollectionView内显示Yes/No?

解决方案

有几种简单的方式可以实现这个需求,以下是常用的三种方案:

方案1:使用值转换器(IValueConverter)

创建一个转换器,将0/1转换为对应文本:

using System;
using Microsoft.Maui.Controls; // Xamarin项目替换为Xamarin.Forms

public class CdToYesNoConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is int cdValue)
        {
            return cdValue == 1 ? "yes" : "no";
        }
        return "no";
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

在XAML资源中声明转换器,修改Label的绑定:

<!-- 先在XAML顶部添加本地命名空间,替换为你的项目命名空间 -->
xmlns:local="clr-namespace:YourAppNamespace"

<CollectionView ItemsSource="{Binding LHItems}">
    <CollectionView.Resources>
        <local:CdToYesNoConverter x:Key="CdToYesNoConverter" />
    </CollectionView.Resources>
    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="models:NewAppliedLeave">
            <VerticalStackLayout>
                <Label Text="{Binding IsCd, Converter={StaticResource CdToYesNoConverter}}" 
                       Grid.Row="0" Grid.Column="4"/>
            </VerticalStackLayout>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

方案2:在模型中添加计算属性

直接在NewAppliedLeave模型里新增只读属性,返回对应文本:

public class NewAppliedLeave
{
    // 原有的IsCd属性
    public int IsCd { get; set; }

    // 新增计算属性
    public string IsCdDisplay => IsCd == 1 ? "yes" : "no";
}

绑定这个新属性即可:

<Label Text="{Binding IsCdDisplay}" Grid.Row="0" Grid.Column="4"/>

方案3:使用DataTrigger

无需额外代码,直接在XAML中通过触发器实现:

<Label Grid.Row="0" Grid.Column="4">
    <Label.Style>
        <Style TargetType="Label">
            <Setter Property="Text" Value="no"/>
            <Style.Triggers>
                <DataTrigger TargetType="Label" 
                             Binding="{Binding IsCd}" 
                             Value="1">
                    <Setter Property="Text" Value="yes"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Label.Style>
</Label>

内容的提问来源于stack exchange,提问作者Lasitha Lankajeewa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 14:05:14