简体   繁体   中英

Replace dynamically BitmapImage in Button (xaml)

I have following code snippet in xaml:

<UserControl x:Class="Ournamespace.OurClassName"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    ...
             d:DesignHeight="250" d:DesignWidth="774" Loaded="UserControl_Loaded">

....
<Button Grid.Column="0" x:Name="Button_NewMarker" Style="{StaticResource ViewpointFlatButtonStyle}" Width="90" Height="65" 
    VerticalAlignment="Top" Click="Button_NewMarker_Click" x:FieldModifier="public" Margin="0,0,0,0" Grid.Row="1">
    <BitmapImage UriSource="Icons/markers_add_disabled.png" />
</Button>

and I have tried to replace image on button dynamically, by loading new image

if( !imgCache.ContainsKey(path) )
{
    BitmapImage bi = new BitmapImage();
    bi.BeginInit();
    bi.UriSource = new Uri(path, UriKind.Relative);
    bi.DownloadFailed += bi_DownloadFailed;
    bi.DecodeFailed += bi_DecodeFailed;
    bi.EndInit();
    imgCache[path] = bi;

}
Button_NewMarker.BeginInit();
Button_NewMarker.Content = imgCache[path];
//Button_NewMarker.Content = oldbmp;
Button_NewMarker.EndInit();

There is no error occurring (overridden events for this) and BitmapImage seems to be replaced - but for some reason it's grey. Images are added to project as resources, and first image loaded seems to be working - but not dynamically replaced one.

I have tried also to use <Image ... > and even <Image ... <ImageBitmap - but all of them are not working - I suspect it has something to do with our control being UserControl.

What I have seen in internet - there is huge amount of recommendations of what and how should be done - I want now this to be done with absolute minimum amount of code - and preferably without using binding and templating. Binding can be proposed as second step after everything is done manually.

If image files are managed as resource files (ie project files which have their Build Action set to Resource ) you should load them by a Resource File Pack URI .

Assuming a project folder Images with an image file Test.png :

var bi = new BitmapImage(new Uri("pack://application:,,,/Images/Test.png"));

Using the file name as key, the abobe would probably look like:

var path = "Test.png";
var uri = "pack://application:,,,/Images/" + path;

imgCache[path] = new BitmapImage(new Uri(uri));

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