ADi
ADi

Reputation: 219

Assign image source in code-behind of XAML control

I have the following xaml

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

I had to write this much messy code to add picture to it.

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);

Because i have to get the images from folder, which will be changing on time to time, i can't put them in resources.

Is there any short way of adding picture in XAML control. i.e

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

in Codebehind

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

Upvotes: 1

Views: 2746

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564383

Your "messy" code is pretty much the code you would need to add an item to a content control. You can't really shorten it, but if you're doing this regularly, refactoring to a method could help reduce the extra code required:

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);
}

You could then just call this as needed, ie:

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

Upvotes: 1

Clemens
Clemens

Reputation: 128061

You could use an ItemsControl that uses a StackPanel as its 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>

You might now add images as easy as shown below, because WPF provides built-in type conversion from string (or Uri) to ImageSource:

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

Upvotes: 1

Related Questions