我有一个包含发票的列表。这些发票有一个方向值,由一个int (incoming = 0, issued = 1)表示。我想在列表中通过颜色区分这些发票。
我尝试使用ValueConverter,但是当我用发票填充列表时,它不起作用,背景颜色保持默认颜色,即使ValueConvert方法在我放置断点时被击中,并且它从列表中恢复所有对象。如果我将边界替换为xaml文件中的任何颜色,它就会工作,背景更改为特定的颜色。
我在这里错过了什么?
我的xaml(只包含相关代码):
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyApp.Views.InvoiceNumberPage"
xmlns:local="clr-namespace:MyApp.ViewModels"
xmlns:converters="clr-namespace:MyApp.Helpers">
<ContentPage.Resources>
<ResourceDictionary>
<converters:InvoiceDirectionColorConverter x:Key="InvoiceDirectionColorConverter"/>
</ResourceDictionary>
<ListView Grid.Row="4" Grid.ColumnSpan="2" ItemsSource="{Binding FoundList}" Margin="20,0">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid BackgroundColor="{Binding Direction, Converter={StaticResource InvoiceDirectionColorConverter}}">
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Text="{Binding InvoiceNumber}" Grid.Row="0" Grid.Column="0"/>
<Label Text="{Binding IssueDate, StringFormat='{0:yyyy.MM.dd}'}" Grid.Row="0" Grid.Column="1"/>
<Label Text="{Binding Company.Name}" Grid.Row="1" Grid.Column="0"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
和ValueConverter:
class InvoiceDirectionColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
SolidColorBrush brush = new SolidColorBrush();
int invoicedirection = (int)value;
if (invoicedirection != null && invoicedirection.Equals(0))
{
brush.Color = Color.Green;
}
else
{
brush.Color = Color.Yellow;
}
return brush;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
正如Jason在他的评论中提到的,您应该返回Color
类型而不是Brush
类型。
class InvoiceDirectionColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int invoicedirection = (int)value;
if (invoicedirection != null && invoicedirection.Equals(0))
{
return Color.Green;
}
else
{
return Color.Yellow;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}