请帮助我理解这一点。我的视图中有以下内容:
<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}">
<Binding Path="CommunityName"
Source="x:Reference communityAndUserLabel" />
<Binding Path="Username"
Source="x:Reference communityAndUserLabel" />
</MultiBinding>
</Label.TextColor>
</Label>
当应用程序运行时,CommunityName和Username显示为按照Label. TextStringFormat指定的格式然而,当满足标准时,不发生颜色变化。我发现这是因为object[] values在开始时似乎没有将任何数据放入CommunityTextColorConvertor.cs文件中,因此所有内容都计算为null/empty。
CommunityTextColorConverter.cs:
using System.Globalization;
namespace Disc.Converters
{
public class CommunityTextColorConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{ // Check if the values are valid if (values == null || values.Length != 2) return Colors.Black;
// Get the community name and username from the values array
string CommunityName = values[0] as string;
// Check if the community name and username are not null or empty
if (string.IsNullOrEmpty(CommunityName))
{
return Colors.PowderBlue; //default color when unset
}
// Define some colors for different communities
Color red = Color.FromRgb(255, 0, 0);
Color green = Color.FromRgb(0, 255, 0);
Color blue = Color.FromRgb(0, 0, 255);
// Return a different color based on the community name
switch (CommunityName.ToLower())
{
case "nintendo":
return red;
case "xbox":
return green;
case "playstation":
return blue;
case "pcgaming":
return Colors.Purple;
case "news":
return Colors.Pink;
default:
return Colors.PowderBlue;
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
// Not implemented
throw new NotImplementedException();
}
}
}
我试过的东西:
- 在Label.TextColor元素中设置BindingPath =“Text”
- 在Label.TextColor元素中设置BindingPath =“CommunityName”(另一个设置Username)
- 再次运行它而不改变任何东西,希望它会神奇地工作,这一次
1条答案
按热度按时间nwlqm0z11#
我能够得到拉入的值,这在技术上是我的问题-所以我想我应该张贴‘解决方案‘作为答案?Julian提到绑定源代码是错误的,这让我走上了正确的道路。它仍然不像我试图做的那样工作(只能让整个字符串显示为一种颜色),但更新的(半)工作代码如下:
NameColorMultiConverter.cs
附带XAML