9

我想要一个 ItemsControl,其中项目水平显示。

但是,无论我将StackPanel与 Orientation="Horizo​​ntal" 还是WrapPanel一起使用,它们仍然会堆叠起来。

如何使 ItemsControl 中的项目水平放置?

替代文字

XAML:

<Window x:Class="TestItemsControl2938.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="400">
    <Window.Resources>
        <DataTemplate x:Key="CustomerListTemplate">
            <StackPanel Width="100" Background="#aaa" Margin="5">
                <TextBlock Text="{Binding LastName}"/>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>       
    <StackPanel>
        <StackPanel Orientation="Horizontal" Background="Orange">
            <ItemsControl ItemsSource="{Binding CustomerList}" ItemTemplate="{StaticResource CustomerListTemplate}"/>
        </StackPanel>
        <WrapPanel Background="Yellow">
            <ItemsControl ItemsSource="{Binding CustomerList}" ItemTemplate="{StaticResource CustomerListTemplate}"/>
        </WrapPanel>
    </StackPanel>
</Window>

代码隐藏:

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; }
    }
}
4

2 回答 2

31

走错路了。自定义 ItemsControl 用来包含其项目的面板:

<ItemsControl>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
             <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>
于 2009-08-04T15:47:14.850 回答
1

你应该使用项目面板。看这里我的回答

于 2009-08-04T15:47:18.690 回答