这是我的代码(您可以在 VS 中创建一个新的 WPF 项目并运行它,只需将 MainWindow 的 XAML 中的 Grid 名称设置为 MainGrid):
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."));
messages.Add(new Message(DateTime.Now, "This is a multi-line message.\nThis is a multi-line message."));
messages.Add(new Message(DateTime.Now, "This is a multi-line message.\nThis is a multi-line message."));
messages.Add(new Message(DateTime.Now, "This is a multi-line message.\nThis is a multi-line message."));
ListView listView = new ListView();
Style style = new Style();
style.TargetType = typeof(ListViewItem);
DataTrigger trigger = new DataTrigger();
trigger.Binding = new Binding("Text");
trigger.Value = "This is a test.";
trigger.Setters.Add(new Setter(ListViewItem.BackgroundProperty, Brushes.Pink));
style.Triggers.Add(trigger);
style.Setters.Add(new Setter(ListViewItem.HeightProperty, 20.0));
style.Setters.Add(new Setter(ListViewItem.MarginProperty, new Thickness(0)));
style.Setters.Add(new Setter(ListViewItem.BorderThicknessProperty, new Thickness(0)));
listView.ItemContainerStyle = style;
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; }
}
}
}
如您所见,由于我将每个 ListViewItem 的高度限制为 20.0,因此多行消息在 ListView 中显示出一种令人讨厌的感觉。我真的只想显示文本消息的第一行。我怎样才能实现这种行为?