c# - 动态加载项源的 WPF DataGrid 垂直滚动条问题
问题描述
问题:除非我在网格上设置静态高度,否则无法显示 DataGrid 的垂直滚动条。我知道以前有人问过类似的问题,但是与其他问题不同,我的示例要简单得多,没有网格列。DataGrid 只是在控件内的 StackPanel 内。就是这样,除了设置静态高度之外,自动、“*”等的组合都不起作用。
这仅仅是 WPF 框架中缺少的一个功能,即它是绑定到网格的 ViewModel 上的可观察集合,当项目添加到 VM 集合时不会通知视图?我是否必须编写自定义属性并将 DataGrid Height 绑定到该属性?
这是我的 XMAL:
<Window x:Class="Monster.Configure"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewModels="clr-namespace:Monster.ViewModels"
xmlns:local="clr-namespace:Monster"
mc:Ignorable="d"
Title="Configure" Width="1200">
<Window.DataContext>
<viewModels:ViewModelMain/>
</Window.DataContext>
<Window.Resources>
<BooleanToVisibilityConverter x:Key="b2v" />
</Window.Resources>
<Grid>
<StackPanel Margin="5">
<Button Name="button_Refresh" Content="Save / Refresh" HorizontalAlignment="Left" Margin="5" Width="100"
Click="button_Refresh_Click"></Button>
<StackPanel Orientation="Horizontal">
<!--Buttons and other junk here-->
</StackPanel>
<Label></Label>
<DataGrid Name="dataGrid_PendingCreation" CanUserAddRows="True" CanUserDeleteRows="True" AutoGenerateColumns="False"
ItemsSource="{Binding URLsForGrid}"
Loaded="dataGrid_PendingCreation_Loaded"
CellEditEnding="dataGrid_PendingCreation_CellEditEnding"
ScrollViewer.CanContentScroll="True"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.HorizontalScrollBarVisibility ="Auto"
Width="Auto" Height="Auto">
<DataGrid.Columns>
<!--Columns and junk here-->
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</Grid>
</Window>
如您所见,允许用户添加新行。这样做时,除非在 DataGrid 中设置了静态高度,否则永远不会显示垂直滚动条。
解决方案
你DataGrid
被包裹在一个StackPanel
(垂直方向)内。垂直方向StackPanel
总是为其子级提供看似无限的可用高度。由于您DataGrid
的 'Height
属性设置为Auto
,它将尽可能大;它永远不会显示垂直滚动条,因为只有在DataGrid
的可用高度(由父级确定)小于实际需要的高度时才会这样做。
解决方案是不要在StackPanel
这里使用 a 。相反,请使用 aGrid
或 a DockPanel
。我通常更喜欢后者,如果我想要实现的只是垂直或水平堆叠孩子,并让一个孩子尽可能地伸展;这是如何完成的:
<Window>
...
<Grid>
...
<DockPanel Margin="5">
<Button DockPanel.Dock="Top" Name="button_Refresh" ... />
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal">
<!--Buttons and other junk here-->
</StackPanel>
<Label DockPanel.Dock="Top"></Label>
<DataGrid Name="dataGrid_PendingCreation" ... />
</DockPanel>
...
</Grid>
...
</Window>
确保这DataGrid
是 DockPanel 中的最后一个孩子并且它没有DockPanel.Dock
属性。这确保了DataGrid
在放置所有其他控件后将获得可用的高度和宽度。
推荐阅读
- c - 如何更改输入链表而不返回
- prometheus - promql 中有没有办法使用 thanos api 获取所有可用的标签名称?
- oracle - 除了 select into 语句之外,还有什么方法可以将选择查询分配给 PL/SQL 中的局部变量?
- javascript - MongoDB 聚合条件 - 根据条件隐藏对象
- javafx - 如何在 javafx 中的某些操作之前显示 processindecator
- r - r-plotly 过滤器按钮以显示所有数据
- javascript - 按字母顺序对对象数组中的元素进行排序(错误)
- javascript - Undefined 不是 React Native 上的对象(评估“this.props.navigation.navigate”)
- javascript - Firebase + React Native:无效的流令牌
- c# - 无法在授权属性上动态发送 Active Directory 组名称