我很苦恼,找不到一个好的示例来动态地创建、填充和样式化ListView。我找到的每个示例都倾向于使用大量的XAML标记和最少量的C#代码来切换运行哪个标记位。这对我来说是不可能的,因为我在编译时不知道列的构成和预期的样式。
我需要的非常简单 - 一个ListView,其中给定行的特定单元格如果值为负数将为红色,如果值为正数则为黑色。然而,直到运行时才知道是哪一行以及它们将是什么颜色(有一个动态/程序化的示例即可)。
我目前拥有的代码(已简化)如下:
string[] columns = new string[] { "Test", "Test2" };
ListView lv = new ListView();
/* Add Columns (works */
GridView viewLayout = new GridView();
foreach (string colName in columns)
{
viewLayout.Columns.Add(new GridViewColumn{ Header = colName });
}
lv.View = viewLayout;
/* Add Items (happy to go the .source path if it's easier) */
foreach (object d in GetData())
{
lv.Items.Add(d);
}
/* Example style, fails */
lv.ItemContainerStyle.Setters.Add(
new Setter(Control.BackgroundProperty, *how do you connect the IValueConverter*)
);