我的窗口中有一个ListView,我绑定到List,现在我想根据该行的值更改特定行的样式。假设我希望其中具有特定值的行具有灰色背景。我怎么能这样做?
<ListView Margin="0 10 0 0"
Height="205"
HorizontalAlignment="Center"
VerticalAlignment="Top"
Width="270"
Name="ElevationList">
<ListView.View>
<GridView>
<GridViewColumn Header="Story"
DisplayMemberBinding="{Binding Path=El}"
Width="100"/>
</GridView>
</ListView.View>
</ListView>
答案 0 :(得分:1)
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();
}
}