当我在ItemsControl中的项目上有背景颜色并将边距设置为 0 时,WPF 会在项目之间留下细线,就好像 ItemsControl 包装管道占用了少量空间一样。我用Snoop检查了可视化树,所有边距都设置为 0,0,0,0。
是什么导致了这些线条,我该如何避免它们?
XAML:
<DockPanel>
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal" Background="Yellow" >
<ItemsControl ItemsSource="{Binding CustomerList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Background="DarkGreen">
<TextBlock Text="{Binding LastName}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<DockPanel Margin="10"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</StackPanel>
</DockPanel>
代码隐藏:
using System.Windows;
using System.ComponentModel;
using System.Collections.ObjectModel;
namespace TestItemsControl2938
{
public partial class Window1 : Window, INotifyPropertyChanged
{
private ObservableCollection<Customer> _customerList = new ObservableCollection<Customer>();
public ObservableCollection<Customer> CustomerList
{
get
{
return _customerList;
}
set
{
_customerList = value;
OnPropertyChanged("CustomerList");
}
}
public Window1()
{
InitializeComponent();
DataContext = this;
CustomerList.Add(new Customer { FirstName = "Jim", LastName = "Jones" });
CustomerList.Add(new Customer { FirstName = "Joe", LastName = "Adams" });
CustomerList.Add(new Customer { FirstName = "Jake", LastName = "Johnson" });
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Street { get; set; }
public string Location { get; set; }
public string ZipCode { get; set; }
}
}
回答:
这是修复,谢谢肯特:
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Background="#ccc" SnapsToDevicePixels="True">
<TextBlock Text="{Binding LastName}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>