有一个带分组的数据网格。但是,如果您运行该程序并调整窗口大小,则表格列的大小不会改变。可能此行为是由于分组中的 Expander 元素造成的。如何使表格列具有动态大小并在调整窗口大小时自动拉伸到全宽?
XML
<DataGrid ItemsSource="{Binding Items, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" SelectionMode="Extended" IsReadOnly="True" CanUserAddRows="False" CanUserDeleteRows="False"
AutoGenerateColumns="False" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Auto">
<DataGrid.GroupStyle>
<!-- Style for groups at top level. -->
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Margin" Value="0,0,0,5"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander IsExpanded="true" Background="DarkGray" BorderBrush="DarkGray" Foreground="Black" BorderThickness="1,1,1,5">
<Expander.Header>
<DockPanel>
<TextBlock FontWeight="Bold" Text="{Binding Path=Name}" Margin="5,0,0,0" Width="100"/>
</DockPanel>
</Expander.Header>
<Expander.Content>
<ItemsPresenter />
</Expander.Content>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</DataGrid.GroupStyle>
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Model.Name, Mode=OneWay}" Width="40*"/>
<DataGridTemplateColumn Header="Added">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Path=Model.Checked, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
查看模型
public class MainViewModel
{
public MainViewModel()
{
_items.Add("Test", new List<MyModel>
{
new MyModel { Name ="val1", Checked = true},
new MyModel { Name ="val2", Checked = false},
});
_items.Add("Test2", new List<MyModel>
{
new MyModel { Name ="val2", Checked = true},
new MyModel { Name ="val4", Checked = false},
});
ItemsSource = new List<GridModel>();
foreach (var item in _items)
{
foreach (var value in item.Value)
{
ItemsSource.Add(new GridModel { Group = item.Key, Model = value });
}
}
_itemsCollectionView = CollectionViewSource.GetDefaultView(ItemsSource);
var t = Items.CanGroup;
_itemsCollectionView.GroupDescriptions.Add(new PropertyGroupDescription("Group"));
_itemsCollectionView.Refresh();
}
private Dictionary<string, List<MyModel>> _items = new Dictionary<string, List<MyModel>>();
public List<GridModel> ItemsSource { get; set; }
private ICollectionView _itemsCollectionView;
public ICollectionView Items
{
get { return _itemsCollectionView; }
set { _itemsCollectionView = value; }
}
}
public class GridModel
{
public string Group { get; set; }
public MyModel Model { get; set; }
}
public class MyModel
{
public string Name { get; set; }
public bool Checked { get; set; }
}
事实证明,有必要删除属性 ScrollViewer.CanContentScroll="True"