WPF应用程序中动态生成的图像控件

时间:2010-02-06 08:53:39

标签: c# wpf

我想在WPF应用程序中动态创建一个Image控件并设置该控件的属性...如Size,location,color,sizemode 我该怎么做?给我任何样本代码..

3 个答案:

答案 0 :(得分:1)

这是一个简单的例子,我已经完成了加载堆栈溢出的徽标。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Loaded += new RoutedEventHandler(MainWindow_Loaded);
    }

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        var webImage = new BitmapImage(new Uri("http://sstatic.net/so/img/logo.png"));
        var imageControl = new Image();
        imageControl.Source = webImage;
        ContentRoot.Children.Add(imageControl);
    }
}

和xaml ......

<Window x:Class="WpfExamples.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 x:Name="ContentRoot">

    </Grid>
</Window>

干杯,

安德鲁

答案 1 :(得分:0)

您想要显示图片文件或流吗?或者你要创建一个图像控件并将其添加到代码中的窗口中?

答案 2 :(得分:0)

来自here,在MSDN上

// Create Image Element
Image myImage = new Image();
myImage.Width = 200;

// Create source
BitmapImage myBitmapImage = new BitmapImage();

// BitmapImage.UriSource must be in a BeginInit/EndInit block
myBitmapImage.BeginInit();
myBitmapImage.UriSource = new Uri(@"C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Water Lilies.jpg");

// To save significant application memory, set the DecodePixelWidth or  
// DecodePixelHeight of the BitmapImage value of the image source to the desired 
// height or width of the rendered image. If you don't do this, the application will 
// cache the image as though it were rendered as its normal size rather then just 
// the size that is displayed.
// Note: In order to preserve aspect ratio, set DecodePixelWidth
// or DecodePixelHeight but not both.
myBitmapImage.DecodePixelWidth = 200;
myBitmapImage.EndInit();
//set image source
myImage.Source = myBitmapImage;