Когда у меня есть фоновые цвета для элементов в 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>
Code-Behind:
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>