由于DataGrid,按钮不可见

时间:2014-05-17 17:44:48

标签: c# wpf xaml datagrid

我有以下xaml代码:

<Window x:Class="DataGridIssue.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:DataGridIssue"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <vm:ViewModel x:Key="ViewModel"/>
    </Window.Resources>
    <Grid>
        <DockPanel VerticalAlignment="Top">
            <Button DockPanel.Dock="Top" Content="Test button 1" HorizontalAlignment="Left"/>
            <DataGrid DockPanel.Dock="Top" AutoGenerateColumns="True" ItemsSource="{Binding Source={StaticResource ViewModel}, Path=TestList}"/>
            <Button DockPanel.Dock="Top" HorizontalAlignment="Left" Content="Test button 2"/>
        </DockPanel>
    </Grid>
</Window>

和C#ViewModel代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;

namespace DataGridIssue
{
    public class ViewModel
    {
        public ObservableCollection<Test> TestList { get; set; }

        public ViewModel()
        {
            TestList = new ObservableCollection<Test>();

            for (int i = 1; i <= 30; i++)
            {
                var item = new Test();
                item.TestString = "Element " + i.ToString();
                TestList.Add(item);
            }
        }
    }

    public class Test
    {
        public string TestString { get; set; }
    }
}

事情是第二个按钮不可见。据我所知,按钮总是位于数据网格的末尾(恰好在窗口之外),如果数据网格没有垂直滚动,则按钮可见。怎么解决这个问题?

编辑:我想避免明确指定高度。

EDIT2:以下是诀窍:

    <Window.Resources>
        <vm:ViewModel x:Key="ViewModel"/>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <Button Grid.Row="0" Content="Test button 1" HorizontalAlignment="Left"/>
        <DataGrid Grid.Row="1" AutoGenerateColumns="True" ItemsSource="{Binding Source={StaticResource ViewModel}, Path=TestList}"/>
        <Button Grid.Row="2" HorizontalAlignment="Left" Content="Test button 2"/>
    </Grid>
</Window>

1 个答案:

答案 0 :(得分:1)

您应该使用Grid三行:

...
 <Window.Resources>
        <vm:ViewModel x:Key="ViewModel"/>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <Button Grid.Row="0" Content="Test button 1" HorizontalAlignment="Left"/>
        <DataGrid Grid.Row="1" AutoGenerateColumns="True" ItemsSource="{Binding Source={StaticResource ViewModel}, Path=TestList}"/>
        <Button Grid.Row="2" HorizontalAlignment="Left" Content="Test button 2"/>
    </Grid>
</Window>