在XAML控件的代码隐藏中分配图像源

时间:2014-01-20 18:43:19

标签: c# wpf xaml

我有以下xaml

<StackPanel x:Name="StackPanelBanner" Grid.Row="1"></StackPanel>

我不得不写这个杂乱的代码来添加图片。

var toplogoBitmap = new BitmapImage();
toplogoBitmap.BeginInit();
toplogoBitmap.UriSource = new Uri(@"" + _appPath + "images/toplogo.png", UriKind.RelativeOrAbsolute);
toplogoBitmap.EndInit();

var toplogoImage = new Image
{
    Source = toplogoBitmap,
    VerticalAlignment = VerticalAlignment.Top,
    HorizontalAlignment = HorizontalAlignment.Left,
    Stretch = Stretch.None
};
StackPanelBanner.Children.Add(toplogoImage);

因为我必须从文件夹中获取图像,这些图像会不时变化,所以我无法将它们放入资源中。

在XAML控件中添加图片有什么简短方法吗?即

<StackPanel source="toplogo" x:Name="StackPanelBanner" Grid.Row="1"></StackPanel>
Codebehind中的

var toplogo = @"" + _appPath + "images/toplogo.png";

2 个答案:

答案 0 :(得分:1)

您可以使用ItemsControl StackPanel作为其ItemsPanel

<ItemsControl x:Name="itemsControl" Grid.Row="1">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Image Source="{Binding}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

您现在可以轻松添加图片,如下所示,因为WPF提供了从string(或Uri)到ImageSource的内置类型转换:

itemsControl.Items.Add(_appPath + "images/toplogo.png");

答案 1 :(得分:1)

您的“杂乱”代码几乎就是将项目添加到内容控件所需的代码。你不能真正缩短它,但如果你经常这样做,重构一个方法可以帮助减少所需的额外代码:

public void AddImageToContainer(string path, Panel parent)
{
    var bmap = new BitmapImage(new Uri(_appPath + path, UriKind.RelativeOrAbsolute));
    var img = new Image
    {
        Source = bmap,
        VerticalAlignment = VerticalAlignment.Top,
        HorizontalAlignment = HorizontalAlignment.Left,
        Stretch = Stretch.None
    };
    parent.Children.Add(img);
}

然后你可以根据需要调用它,即:

AddImageToContainer("images/toplogo.png", StackPanelBanner);