1、以资源的形式定义列
2、根据配置或用户需要,将列添加到ListView中
xaml:
<UserControl.Resources>
<GridViewColumn x:Key="SerialNumber"
Width="2"
Header="序号">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock HorizontalAlignment="Center"
VerticalAlignment="Center"
Text="{Binding SerialNumber, Mode=TwoWay}"
TextWrapping="Wrap" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn x:Key="Name"
Width="2"
Header="名称">
<!-- content-->
</GridViewColumn>
...
</UserControl.Resources>
<ListView x:Name="LvData" />
.xaml.cs
private async void DataManager_Loaded(object sender, RoutedEventArgs e)
{
var heads = await GetUserTableHeadDisplay();
var allWidthPercent = heads.Sum(x => x.WidthPercent);
((GridView)LvData.View)?.Columns.Clear();
var newColumn = new GridView();
foreach (var head in heads)
{
var col = Resources[head.ColumnHeadCode] as GridViewColumn;
col.Width = (this.ActualWidth / allWidthPercent) * head.WidthPercent;
newColumn.Columns.Add(col);
}
LvData.View = newColumn;
}