我正在尝试根据ListView的项目值设置不同的颜色,到目前为止我做了什么:
<ListView ItemsSource="{Binding Collections}">
<ListView.Resources>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource SignColorConverter}}" />
</Style>
</ListView.Resources>
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Header="Item1" DisplayMemberBinding="{Binding Item1}"/>
<GridViewColumn Header="Item2" DisplayMemberBinding="{Binding Item2}"/>
转换器:
public class SignColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var input = System.Convert.ToInt32(value as string);
//this method simply check if the value is between a range.
if (GeneralUtility.IsInRange(input, 0, 20))
{
return Brushes.Red;
}
else
{
return DependencyProperty.UnsetValue;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
问题是转换器中的input
值是0
。我做错了什么?
感谢您的帮助。
更新
Collection
属性包含以下值:
public List<Collection> Collection
{
public Item1 { get; set; }
public Item2 { get; set; }
}
基本上我需要传递样式:
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource SignColorConverter}}" />
</Style>
Item
的每个Collection
值,并评估转换器上的值。
答案 0 :(得分:1)
您的XAML将ListViewItem
绑定到setter。当您的IValueConverter
转换ListViewItem
类型时,它会返回0(如果您使用int.TryParse()
,则会返回false
)。您缺少的是您必须将setter绑定到ListViewItem
中的属性。例如,如果您的ListViewItem
是:
class item
{
public object Item1 {get;set;}
public object Item2 {get;set;}
public int Color {get;set;}
}
然后您的XAML可以是:
<ListView ItemsSource="{Binding Collections}">
<ListView.Resources>
<local:SignColorConverter x:Key="SignColorConverter"/>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Background" Value="{Binding Color, Converter={StaticResource SignColorConverter}}"/>
</Style>
</ListView.Resources>
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Header="Item1" DisplayMemberBinding="{Binding Item1}"/>
<GridViewColumn Header="Item2" DisplayMemberBinding="{Binding Item2}"/>
...
或者如果您必须评估多个项目属性,您的XAML可以与OP保持一致:
...
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}}, Converter={StaticResource SignColorConverter}}"/>
</Style>
...
然后您必须将ListViewItem
评估为IValueConverter
中的相应类型:
public class SignColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var input = (item)value;
if (input != null)
{
int item1 = int.Parse(input.Item1);
int item2 = int.Parse(input.Item2);
//Your logic here
return Brushes.Red;
}
else
{
return DependencyProperty.UnsetValue;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}