我的问题类似于:防止 WPF 控件扩展到可视区域之外不同之处在于,接受的解决方案(特定于 StackPanel 的问题(对我并没有多大帮助。
我有一个窗口,目前只包含以下网格:
<Grid ShowGridLines="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="265"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="147*"/>
<RowDefinition Height="173*"/>
</Grid.RowDefinitions>
<Button Content="Button" HorizontalAlignment="Right" VerticalAlignment="Bottom" Width="75" Click="Button_Click" Grid.Row="1" Grid.Column="1"/>
<local:BatteryGraphicsView x:Name="batView" HorizontalAlignment="Stretch" ClipToBounds="True" Width="265"/>
</Grid>
我现在希望,如果我的 GraphicsView 延伸到其列的宽度,则会显示滚动条,并且控件不会将其绘制在列的边界之外。
只要我按下按钮,就会发生这种情况。用户控件基本上是一个包含WinFormsHosts的网格,当按下按钮时,会为网格创建更多列,因此网格会增长
(用户控制网格 xaml(
<ScrollViewer VerticalScrollBarVisibility="Hidden" HorizontalScrollBarVisibility="Auto" ClipToBounds="True">
<Grid x:Name="Maingrid" ClipToBounds="True">
<Grid.RowDefinitions>
<RowDefinition Height="40*"/>
<RowDefinition Height="20*"/>
<RowDefinition Height="40*"/>
</Grid.RowDefinitions>
<WindowsFormsHost x:Name="host1" />
<WindowsFormsHost x:Name="host2" Grid.Row="2"/>
</Grid>
</ScrollViewer>
虽然 Scollviewer 意识到它需要自己显示它,但 mainGrid 无论如何都会显示在列的边界之外。在多个相关帖子中,我看到您需要将"ClipToBounds"属性设置为 true,但我为每个控件设置了该属性,但仍然没有任何反应。
问题是UserControl中的ScrollViewer不知道GridColumn和GridRow的大小是多少。
您可以做两件事。
1:为列指定最大宽度和行的最大高度
2:不要在用户控件中添加 scrollViewer,而是将其添加到网格中并为其提供高度和宽度。