Frage

So I am new to .NET and WPF, and was hoping someone could tell me what I'm doing wrong. I have a WPF application which is basically just a data grid. For the life of me, I can't figure out how to get the DataGrid to resize automatically whenever the parent window changes size, without having to resort to writing a bunch of code to monitor the window resize events. On OS X/Cocoa/Interface Builder this is fairly easy and straight forward, and I can only assume WPF has a similar feature.

<Window x:Class="MyClass.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="358" Width="542">
    <Grid>
        <DataGrid x:Name="mydatagrid" ItemsSource="{Binding}" AutoGenerateColumns="true" Height="328" Width="534"/>
    </Grid>
</Window>
War es hilfreich?

Lösung

So I figured it out thanks to WPF Grid allow controls inside to auto size width/height

Edit: So to address the comments (sorry about this still new here). What I was doing wrong, was not defining Grid.ColumnDefinitions (or RowDefinitions depending on how you're organizing things), and specifying the Grid.Column (or Row) numbers for the controls inside of the Grid. Here is an example with 2 DataGrids and a GridSplitter. Also you should specify the width (or height if a row) in the ColumnDefinition (or RowDefinition) instead of in the control itself.

<Grid Height="Auto" Width="Auto">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <DataGrid x:Name="myDataGrid1" Grid.Column="0" Margin="0,0,0,0" ItemsSource="{Binding}" HeadersVisibility="Column" IsReadOnly="True" AutoGeneratingColumn="OnAutoGeneratingColumn"/>
    <GridSplitter Grid.Column="1" Width="5" HorizontalAlignment="Center" VerticalAlignment="Stretch"/>
    <DataGrid x:Name="myDataGrid2" Grid.Column="2" Margin="0,0,0,0" ItemsSource="{Binding}" HeadersVisibility="Column" IsReadOnly="True" AutoGeneratingColumn="OnAutoGeneratingColumn"/>
</Grid>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top