今天在项目中遇到了一个问题,datagrid 不出现滚动条了,拿出来给大家分享下,以作前车之鉴。
很简单的布局代码如下
<Window x:Class="DataGrid_AutoSize.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="500" Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="376*" />
<ColumnDefinition Width="402*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="65" />
<RowDefinition Height="396*" />
</Grid.RowDefinitions>
<Border BorderBrush="Silver" BorderThickness="1" HorizontalAlignment="Stretch" Margin="5" Name="border1" VerticalAlignment="Top" CornerRadius="5" Height="50" Grid.ColumnSpan="2">
<TextBlock Name="textBlock1" Text="DataGrid ScrollBar Demo" Margin="15,15,0,0" />
</Border>
<Grid Grid.Row="1" HorizontalAlignment="Stretch" Name="grid1" VerticalAlignment="Stretch">
<DataGrid AutoGenerateColumns="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" x:Name="SrollBarDataGrid">
<DataGrid.Columns>
<DataGridTextColumn Width="100" Binding="{Binding id}"/>
<DataGridTextColumn Width="100" Binding="{Binding text}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
<StackPanel Grid.Column="1" Grid.Row="1" HorizontalAlignment="Stretch" Name="stackPanel1" VerticalAlignment="Stretch">
<DataGrid AutoGenerateColumns="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" x:Name="NoSrollBarDataGrid">
<DataGrid.Columns>
<DataGridTextColumn Width="100" Binding="{Binding id}"/>
<DataGridTextColumn Width="100" Binding="{Binding text}"/>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</Grid>
</Window>
后台代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.ObjectModel;
namespace DataGrid_AutoSize
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Init();
}
private void Init()
{
ObservableCollection<Test> mytestdata = new ObservableCollection<Test>();
for(int i=0;i<200;i++)
{
mytestdata.Add(new Test(){id=i.ToString(), text="name"+i.ToString()});
}
SrollBarDataGrid.ItemsSource = mytestdata;
NoSrollBarDataGrid.ItemsSource = mytestdata;
}
}
class Test
{
public string id { get; set; }
public string text { get; set; }
}
}
运行就可以看到右边的 datagrid不会出现滚动条了
原因也比较简单 就是因为右边的布局用了StackPanel
查了下微软文档http://msdn.microsoft.com/zh-cn/library/ms754213
可以看出StackPanel实际上是在水平或者垂直方向正无穷大
导致datagrid认为它的父容器在垂直方向无穷大 所以就没法出现滚动条了
相信很多人都会出现这类情况 在datagrid外面套stackpanel布局吧
所以如果想出现滚动条 就千万别在datagrid外面套stackpanel布局 切记切记~~~~~
小弟才疏学浅,刚刚上手wpf,欢迎大家多交流、批评指正。