XAML代碼:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:sampleApp="clr-namespace:WpfApplication1">
<Window.Resources>
<sampleApp:NumberToBGColorConverter x:Key="NumberBGConverter"/>
</Window.Resources>
<Grid>
<ListView ItemsSource="{Binding ListViewItems}">
<ListView.ItemTemplate>
<DataTemplate DataType="{x:Type sampleApp:Number}">
<Grid Background="{Binding NumberValue,Converter={StaticResource NumberBGConverter}}" Height="20" Width="250">
<TextBlock Text="{Binding NumberValue}" FontWeight="SemiBold"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
C#代碼:
public partial class MainWindow : Window
{
private List<Number> m_ListViewItems;
public List<Number> ListViewItems
{
get { return m_ListViewItems; }
set { m_ListViewItems = value; }
}
public MainWindow()
{
InitializeComponent();
DataContext = this;
ListViewItems = new List<Number>();
ListViewItems.Add(new Number() { NumberValue = 1 });
ListViewItems.Add(new Number() { NumberValue = 2 });
ListViewItems.Add(new Number() { NumberValue = 3 });
ListViewItems.Add(new Number() { NumberValue = 4 });
}
}
public class Number
{
private int m_NumberValue;
public int NumberValue
{
get { return m_NumberValue; }
set { m_NumberValue = value; }
}
}
public class NumberToBGColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var number = (int)value;
if (number % 2 == 0)
return "Gray";
else
return "Yellow";
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
根據結果的數量,你可以使用自定義的'IValueConverter'。 – Unflux 2014-11-23 23:14:24