Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set image programmatically on button

I have issue with set-up image programmatically on button. I have next WPF button:

<Button Name="MyBtn" x:FieldModifier="public" HorizontalAlignment="Center" VerticalAlignment="Center" Click="FlashOnOf_Click" Height="256" Width="256" BorderBrush="{x:Null}"/>

and try to set-up image on it with next cases:

        var brush = new ImageBrush();
        brush.ImageSource = new BitmapImage(new Uri("ms-appx://Assets/light_bulb_off.png"));
        brush.Stretch = Stretch.Fill;

        MyBtn.Background = brush;

one more case:

        MyBtn.Content = new Image
        {
            Source = new BitmapImage(new Uri("ms-appx://Assets/light_bulb_off.png")),
            VerticalAlignment = VerticalAlignment.Center,
            Stretch = Stretch.Fill,
            Height = 256,
            Width = 256
        };

Also with no luck. Any ideas where i've made mistake?

like image 269
Ted Avatar asked Oct 24 '25 09:10

Ted


2 Answers

You should set image like this:

private void btn_Click(object sender, RoutedEventArgs e)
{
    btn.Content = new Image
    {              
        Source = new BitmapImage(new Uri("/WpfApplication1;component/image/add.jpg", UriKind.Relative)),
        VerticalAlignment = VerticalAlignment.Center,
        Stretch = Stretch.Fill,
        Height = 256,
        Width = 256
    };
}

where Uri("/WpfApplication1;component/image/add.jpg" is address to image and WpfApplication is the name of your WPF Application, image is the folder, add.jpg is the name of image.

The basic approach looks like this:

Button myButton = new Button
{
    Width = 50,
    Height = 50,
    Content = new Image
    {
        Source = new BitmapImage(new Uri("image source")),
        VerticalAlignment = VerticalAlignment.Center
    }
};
like image 145
StepUp Avatar answered Oct 26 '25 22:10

StepUp


You need to specify the UriKind on creating BitmapImage

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        MyBtn.Content = new Image
        {
            Source = new BitmapImage(new Uri("/Assets/Imagename.png", UriKind.RelativeOrAbsolute)),
            VerticalAlignment = VerticalAlignment.Center,
            Stretch = Stretch.Fill,
            Height = 256,
            Width = 256
        };
    }

Also please check your image using.

<Image Height="256" Width="256" Source="/Assets/Imagename.png" />
like image 37
asitis Avatar answered Oct 27 '25 00:10

asitis