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

使用IMultiValueConverter时object[] values为空,视图直接绑定正常

问题解决:Label的MultiBinding颜色转换器接收不到值

问题根源

你给TextColor的MultiBinding设置了Source="x:Reference communityAndUserLabel",这意味着绑定的是Label控件本身,但Label并没有CommunityName和Username这两个属性——这两个属性是在你的ViewModel里的,所以绑定根本取不到值,导致转换器的values数组为空。而Text的MultiBinding没有指定Source,默认绑定当前的DataContext(也就是ViewModel),所以能正常拿到数据。

修复方案

把TextColor的MultiBinding里的Source="x:Reference communityAndUserLabel"删掉,让它和Text的绑定逻辑一致,默认绑定ViewModel的属性:

<Label 
    x:Name="communityAndUserLabel"
    Grid.Row="2"
    Grid.Column="1"
    FontAttributes="None"
    VerticalOptions="End">
    <Label.Text>
        <MultiBinding StringFormat="{}{0} • {1}">
            <Binding Path="CommunityName" />
            <Binding Path="Username" />
        </MultiBinding>
    </Label.Text>
    <Label.TextColor>
        <MultiBinding Converter="{StaticResource CommunityTextColorConverter}">
            <!-- 移除错误的Source配置,直接绑定ViewModel属性 -->
            <Binding Path="CommunityName" />
            <Binding Path="Username" />
        </MultiBinding>
    </Label.TextColor>
</Label>

额外优化建议

看你的转换器代码,实际只用到了CommunityName,Username并没有参与颜色判断逻辑。如果不需要Username来决定颜色,完全可以把MultiBinding改成单值绑定,让代码更简洁:

  1. 将转换器改为单值转换器:
using System.Globalization;

namespace Disc.Converters
{
    public class CommunityTextColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string communityName = value as string;
            if (string.IsNullOrEmpty(communityName))
                return Colors.PowderBlue;

            return communityName.ToLower() switch
            {
                "nintendo" => Color.FromRgb(255, 0, 0),
                "xbox" => Color.FromRgb(0, 255, 0),
                "playstation" => Color.FromRgb(0, 0, 255),
                "pcgaming" => Colors.Purple,
                "news" => Colors.Pink,
                _ => Colors.PowderBlue
            };
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
  1. Label的TextColor改为单值绑定:
<Label.TextColor>
    <Binding Path="CommunityName" Converter="{StaticResource CommunityTextColorConverter}" />
</Label.TextColor>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 18:05:24