更好的方法是使用
UniformGrid
作为
ItemsPanel
的
ListView
.
<ListView>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="3" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
...
</ListView>
下面是使用
ListBox
而不是
列表视图
,如评论中所述。我建议您这样做,除非您需要
列表视图
,因为它会更有表现力。
它使用
AgentOctal.WpfLib
基础的nuget包(我是这个包的作者)
ViewModel
类提供属性更改通知和命令支持。您应该能够替换任何正确实现的工作方法
INotifyPropertyChanged
不过。
XAML:
<Window
x:Class="ColumnsTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ListViewColumns"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800"
Height="450"
mc:Ignorable="d">
<Window.DataContext>
<local:MainWindowVm />
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ListBox
Grid.Row="0"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Stretch"
ItemsSource="{Binding Path=People}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="3" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Border
Height="{Binding RelativeSource={RelativeSource Self}, Path=ActualWidth}"
Margin="4"
BorderBrush="Black"
BorderThickness="1">
<TextBlock Text="{Binding Path=Name}" />
</Border>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button
Grid.Row="1"
Command="{Binding Path=AddPersonCommand}"
Content="Add Person" />
</Grid>
</Window>
视图模型:
namespace ColumnsTest
{
using System.Windows.Input;
using AgentOctal.WpfLib;
using AgentOctal.WpfLib.Commands;
class MainWindowVm : ViewModel
{
public MainWindowVm()
{
People = new ObservableCollection<PersonVm>();
}
public ObservableCollection<PersonVm> People { get; }
private ICommand _addPersonCommand;
public ICommand AddPersonCommand
{
get
{
return _addPersonCommand ?? (_addPersonCommand = new SimpleCommand((obj) =>
{
People.Add(new PersonVm() { Name = Guid.NewGuid().ToString() });
}));
}
}
class PersonVm : ViewModel
{
private string _name;
public string Name
{
get { return _name; }
set { SetValue(ref _name, value); }
}
}
}
结果如下: