Reputation: 77
<Grid Name="PlotGrid" Margin="50,50,50,50">
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="500" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<Canvas Name="canvas" Grid.Row="0" Grid.Column="0" />
<Border Name="firstborder"
Grid.Column="0"
Grid.Row="0"
BorderBrush="Black"
BorderThickness="1">
</Border>
<Border Name="secondborder"
Grid.Column="1"
Grid.Row="0"
BorderBrush="Black"
BorderThickness="1">
</Border>
<Border Name="thirdborder"
Grid.Column="0"
Grid.Row="1"
BorderBrush="Black"
BorderThickness="1">
</Border>
<Border Name="fourthborder"
Grid.Column="1"
Grid.Row="1"
BorderBrush="Black"
BorderThickness="1">
</Border>
</Grid>
I am dynamically adding an image to the canvas above, which is inside a grid cell:
try
{
if ((myStream = openFileDialog.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
image1.Source = new BitmapImage(new Uri( openFileDialog.FileName));
canvas.Children.Add(image1);
}
}
}
My expectation is that the imported image will remain inside the canvas and inside the grid cell that contains the canvas. But it occupies a huge space well beyond the grid cell. How can I keep the imported image within the confines of the grid cell?
Upvotes: 0
Views: 417
Reputation: 6783
You need to set the image size, otherwise it will be full size
image1.Stretch = Stretch.Uniform;
image1.StretchDirection = StretchDirection.Both;
image1.BeginInit();
image1.Source = new BitmapImage(new Uri( openFileDialog.FileName));
image1.Width = canvas.ActualWidth;
image1.Height = canvas.ActualHeight;
image1.EndInit();
You may also need to add code to handle resizing of the grid.
Upvotes: 1
Reputation: 1470
Perhaps this might work:
...
image1.Stretch = Stretch.Uniform;
image1.StretchDirection = StretchDirection.Both;
image1.BeginInit();
image1.Source = new BitmapImage(new Uri( openFileDialog.FileName));
image1.EndInit();
canvas.Children.Add(image1);
Upvotes: 0