Datagrid列的宽度WPF

时间:2015-01-21 15:31:49

标签: c# wpf datagrid

我在WPF数据网格上设置宽度有问题,我有2列,一个用于名称,一个用于电子邮件,我喜欢两者至少100,但如果名称更长,我喜欢它采取尽可能多的根据需要空间。现在两者都只是结束了100宽度,无论数据网格本身有多宽。这是我尝试的方式:

已编辑的代码:

<StackPanel>
    <DataGrid Name="MemberDataGrid" Margin="10,10,10,10" ColumnWidth="*" AutoGenerateColumns="False" ItemsSource="{Binding}" SelectionMode="Single">
        <DataGrid.Columns>
            <DataGridTextColumn MinWidth="30" Width="Auto" Header="Name" Binding="{Binding Path=Name}" />
            <DataGridTextColumn MinWidth="30" Width="*" Header="Email" Binding="{Binding Path=Email}" />
        </DataGrid.Columns>
    </DataGrid>
    <StackPanel Orientation="Horizontal">
        <Button Name="SelectMemeberButton" Click="SelectMemeberButton_Clicked" Margin="10,10,10,10" HorizontalAlignment="Center" Content="Add member"></Button>
        <Button Name="RemoveMemeberButton" Margin="0,10,0,10" HorizontalAlignment="Center" Content="Remove member" Click="RemoveMemeberButton_Clicked"></Button>
    </StackPanel>
</StackPanel>

1 个答案:

答案 0 :(得分:0)

我的问题中缺少一些东西,我看不出重点。如果我看着你的窗户,我会觉得一切都按预期工作。

这是我使用的代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        DataContext = new Person[] {
            new Person() { Name = "Paul Leary", Email="paul@contoso.com" },
            new Person() { Name = "Andy Dale", Email="andy@contoso.com" },
            new Person() { Name = "Mike 'The Firestarter' Douglas", Email = "an_incredibly_long_email_address@contoso.com" }
        };

    }
}

这就是窗口:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="600">

    <StackPanel Margin="4">
        <DataGrid Name="MemberDataGrid" Margin="10,10,10,10" ColumnWidth="*" AutoGenerateColumns="False" ItemsSource="{Binding}" SelectionMode="Single">
            <DataGrid.Columns>
                <DataGridTextColumn x:Name="Col1" MinWidth="100" Width="Auto" Header="Name" Binding="{Binding Path=Name}" />
                <DataGridTextColumn x:Name="Col2" MinWidth="100" Width="*" Header="Email" Binding="{Binding Path=Email}" />
            </DataGrid.Columns>
        </DataGrid>
        <TextBlock Text="{Binding ElementName=Col1, Path=ActualWidth, Mode=OneWay}" Margin="2" />
        <TextBlock Text="{Binding ElementName=Col2, Path=ActualWidth, Mode=OneWay}" Margin="2" />
    </StackPanel>
</Window>

如果运行此代码,您可以看到第一列的宽度约为164。同时第二列适合所有剩余空间(约384)。那么,这段代码是否以您需要的方式工作?