Silverlight - DataGrid in Scrollviewer, Column.Wid

2019-02-23 17:11发布

问题:

When I have the following setup, the last column having a width of * causes the datagrid to create huge horizontal scrollbars (extends grid to several widths of the screen). I'm not really sure why this is, but I really need a way to avoid that. I don't want to have to "simulate" column's with * lengths.

edit: Apparently I'm not the only one who noticed this. http://connect.microsoft.com/VisualStudio/feedback/details/559644/silverlight-4-datagrid-star-column-width

Xaml:

<ScrollViewer Padding="0" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"  >
    <sdk:DataGrid AutoGenerateColumns="False" x:Name="dg"/>
</ScrollViewer>

Code:

private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
        dg.Columns.Add(new DataGridTextColumn { Binding = new Binding("A"), Header = "A" });
        dg.Columns.Add(new DataGridTextColumn { Binding = new Binding("B"), Header = "B" });
        dg.Columns.Add(new DataGridTextColumn { Binding = new Binding("C"), Header = "C" });
        dg.Columns[2].Width = new DataGridLength(1, DataGridLengthUnitType.Star);
        dg.ItemsSource = new[] 
        {
            new I { A = "SAF", B = "SAF", C = "SAF" },
            new I { A = "SAF", B = "SAF", C = "SAF" },
            new I { A = "SAF", B = "SAF", C = "SAF" }
        };
    }

    public class I
    {
        public string A { get; set; }
        public string B { get; set; }
        public string C { get; set; }
    }

回答1:

If you remove

dg.Columns[2].Width = new DataGridLength(1, DataGridLengthUnitType.Star);

the problem should go away. Can I ask why you want the last column to take the rest of the space? The column actually knows to resize itself properly to fit its cell size and column header size.

Also, if you don't specify the column's width, then you don't really need a scrollviewer to scroll and see all the columns. The datagrid has a scrollviewer built in and when there are columns out of the screen the horizontal scrollbar will apear.

I hope this helps. :)



回答2:

you need to put a maxwidth on the scrollviewer? otherwise width is defaulted to auto and maxwidth is infinity