Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In WPF program, I use “Toolbox Image” to display a photo by clicking “Button”. The created box size in “Toolbox Image” is smaller than the actual size of that photo. When choosing “Stretch = UniformToFill”, I can only see a part of the photo (the upper left-hand corner of photo). So how to make a central part of the photo is displayed in the box size without changing “Stretch” and the size of the box?
linkmediafire

Code XML
XML
<Window x:Class="example.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Content="Button" HorizontalAlignment="Left" Height="42" Margin="408,36,0,0" VerticalAlignment="Top" Width="83" Click="Button_Click"/>
        <Image Name="image" HorizontalAlignment="Left" Height="57" Margin="25,36,0,0" VerticalAlignment="Top" Width="275" Stretch="UniformToFill"/>
        <Image Name="image2" HorizontalAlignment="Left" Height="168" Margin="25,141,0,0" VerticalAlignment="Top" Width="275" Stretch="Fill"/>
        <Label Content="image1" HorizontalAlignment="Left" Height="26" Margin="25,10,0,0" VerticalAlignment="Top" Width="47"/>
        <Label Content="Image2" HorizontalAlignment="Left" Height="25" Margin="25,111,0,0" VerticalAlignment="Top" Width="47"/>

    </Grid>
</Window>



Code C#

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace example
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            image.Source = new BitmapImage(new Uri(@"C:\Users\doduc_000\Desktop\a.jpg"));
            image2.Source = new BitmapImage(new Uri(@"C:\Users\doduc_000\Desktop\a.jpg"));
        }
    }
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900