我似乎无法把头绕在什么东西上。假设我的代码中有以下逻辑:
namespace WPFTesting
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
ObservableCollection<Message> messages = new ObservableCollection<Message>();
public MainWindow()
{
InitializeComponent();
messages.Add(new Message(DateTime.Now, "This is a test."));
ListView listView = new ListView();
GridView gridView = new GridView();
listView.View = gridView;
GridViewColumn timeStampColumn = new GridViewColumn();
timeStampColumn.DisplayMemberBinding = new Binding("Date");
GridViewColumnHeader timeStampHeader = new GridViewColumnHeader();
timeStampHeader.Content = "Time";
timeStampColumn.Header = timeStampHeader;
gridView.Columns.Add(timeStampColumn);
GridViewColumn messageColumn = new GridViewColumn();
messageColumn.DisplayMemberBinding = new Binding("Text");
GridViewColumnHeader messageHeader = new GridViewColumnHeader();
messageHeader.Content = "Message";
messageColumn.Header = messageHeader;
gridView.Columns.Add(messageColumn);
Binding binding = new Binding();
binding.Source = messages;
listView.SetBinding(ItemsControl.ItemsSourceProperty, binding);
MainGrid.Children.Add(listView);
}
public class Message
{
public Message(DateTime aDate, String aText)
{
Date = aDate;
Text = aText;
}
public DateTime Date { get; set; }
public String Text { get; set; }
}
}
}
如何以编程方式设置我的 ListView 的样式,以便所有行都具有特定的背景颜色和高度?请注意,我想避免在 ListView 的 Items 列表上执行 foreach 循环并设置每个 ListViewItem 的属性,因为该列表可能有很多项目,而且这可能很昂贵。相反,是否没有某种方法可以使用 Style 类或一些运行时逻辑以编程方式执行此操作?