简体   繁体   中英

How do you set a Xaml defined, Window.Resource Image programmatically?

I have a xaml file that has a series of resources that I use in my window. Specifically, I have two Image objects. Instead of encoding a URI location, I need to set these images in the constructor of my Window. How can I do this?

I've searched and searched, and I've tried to set the image .Source property. Nothing has worked. For reference, here is how these images are declared in my xaml file:

<Window.Resources>
    <Image x:Key="iUpdate" />
    <Image x:Key="iDelete" />
</Window.Resources>

And here is how they are used for a button's content:

                <DataTemplate>
                    <DockPanel>
                        <Button Name="UpdateChange" Content="{StaticResource iUpdate}" Width="24" />
                        <Button Name="DeleteChange" Content="{StaticResource iDelete}" Width="24" />
                        <Label Content="{Binding name}" />
                    </DockPanel>
                </DataTemplate>

Here is my failed attempt at setting the image's source.

        //In my constructor...
        // iUpdate is a property on the Window
        iUpdate = (Image)FindResource("iUpdate");
                    iUpdate = new Image();
        iUpdate.Source = ImageHelpers.ConvertBitmapToImageSource(Common.LoadImage("edit.ico"));

FYI, I can't set the source in my xaml file because the call to Common.LoadImage(...) is a special call that resolves the location of the file. This could vary significantly from user-to-user, which is why the helper-method exists in the first place.

Instead of using Image controls as resources, you could declare and bind to two properties in your MainWindow class.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        UpdateImage = ImageHelpers.ConvertBitmapToImageSource(...);
        DeleteImage = ImageHelpers.ConvertBitmapToImageSource(...);

        InitializeComponent();
    }

    public ImageSource UpdateImage { get; set; }
    public ImageSource DeleteImage { get; set; }
}

You would bind to these properties by assigning a Name to the Window

<Window ... x:Name="window">

and declare an ElementName binding:

<Button ...>
    <Button.Content>
        <Image Source="{Binding UpdateImage, ElementName=window}"/>
    </Button.Content>
</Button>

And to answer your question, your problem is that you assign a new Image instance to the iUpdate field right after assigning it to the resource instance. Your code should have looked like this:

iUpdate = (Image)Resources["iUpdate"];
iUpdate.Source = ImageHelpers.ConvertBitmapToImageSource(...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM