Reputation: 696
I'm creating a simple App, in which I instantiate elements of a custom class in runtime (the class consists of some Control elements: Textblocks, Grids). Since my working area could easily be overpopulated, I want the main Grid of my App scrollable.
I encapsulated my Grid in a Scroll Viewer, and I intend to increase the Width and the Height of the Grid this way making the Horizontal and Vertical Scrollbars appear. My problem is, however, that I don't know how to check if the instance of my custom class is entirely within the working area, or parts of it stretch out of it. I found a method in SO that could solve my problem HERE, but because I have many elements, I would have to check every single one of them. Is there another method that would go easy on performance?
Also, I have to know to what extent my element goes beyond the area, so that I only increase the size of the grid accordingly. I'm new to WPF, so any suggestions are much appreciated!
Here is my idea schematically: Here is the relevant part of my XAML:
<ScrollViewer VerticalScrollBarVisibility="Visible"
HorizontalScrollBarVisibility="Auto"
CanContentScroll="True">
<Grid
x:Name="MainGrid"
Background="Transparent"
MouseLeftButtonUp="grid_MouseLeftButtonUp">
<ItemsControl>
<!--HERE I HAVE A NUMBER OF OTHER ELEMENTS PREDEFINED-->
</ItemsControl>
<Grid.ContextMenu>
<!--HERE I HAVE CONTEXTMENU ELEMENTS-->
</Grid.ContextMenu>
</Grid>
</ScrollViewer>
Upvotes: 1
Views: 3349
Reputation: 12906
Grid should be able to handle auto sizing for you if you use the Margin property of the items to position them. An example where items do not fully fit into view:
<Window x:Class="WpfApplication1.MainWindow"
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:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="400" Width="400">
<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
<Grid x:Name="MainGrid" Background="Transparent">
<Border Background="Blue" Width="250" Height="250" Margin="350 0 0 0" HorizontalAlignment="Left" VerticalAlignment="Top"></Border>
<Border Background="Red" Width="250" Height="250" Margin="0 150 0 0" HorizontalAlignment="Left" VerticalAlignment="Top"></Border>
</Grid>
</ScrollViewer>
</Window>
The above example makes the scrollbars visible:
There's no scrollbars if content fits the view:
There's some other options available, like using a little modified Canvas. You can find more examples from here: WPF: How to make canvas auto-resize?
Upvotes: 2