RStyle
RStyle

Reputation: 885

Setting image in runtime WPF

I have a template in app.xaml. During runtime, i want to create a button and apply this template. I also want to set the Image source during runtime.

<Application.Resources>
        <ControlTemplate x:Key="btemp2" TargetType="{x:Type Button}">
            <Image x:Name="myimage" HorizontalAlignment="Center" Height="84" VerticalAlignment="Center" Width="100" Margin="10,-17.5,7,-24.5"  Stretch="UniformToFill"/>
        </ControlTemplate>
    </Application.Resources>

runtime code:

Button newButton = new Button();
newButton.Width = 100;
newButton.Height = 50;
newButton.Template = (ControlTemplate)TryFindResource("btemp2");
System.Windows.Controls.Image i = newButton.Template.FindName("myimage",this) as System.Windows.Controls.Image;

Bitmap bmp = GetIconImageFromFile(fileName);
BitmapSource src = GetBitmapImageFromBitmap(bmp);
i.Source = src;
stack.Children.Add(newButton);

It does not work as expected. Breakpoint does not reach

Bitmap bmp = GetIconImageFromFile(fileName);

Upvotes: 4

Views: 93

Answers (2)

bars222
bars222

Reputation: 1660

You can use Binding to set image. So you should change ControlTemplate. In that example we using Button Tag property to set image Source.

<ControlTemplate x:Key="btemp2" TargetType="{x:Type Button}">
    <Image x:Name="myimage" HorizontalAlignment="Center" Height="84" VerticalAlignment="Center" Width="100" Margin="10,-17.5,7,-24.5"  Stretch="UniformToFill"
                    Source="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=Tag}"/>
</ControlTemplate>

And the Button creating code should look like this.

Button newButton = new Button();
newButton.Width = 100;
newButton.Height = 50;
newButton.Template = ( ControlTemplate )TryFindResource( "btemp2" );
tempGrid.Children.Add( newButton );
BitmapImage image = new BitmapImage(new Uri("pack://application:,,,/WPFTest;component/Images/GPlus.png"));
newButton.Tag = image;

Upvotes: 4

AnjumSKhan
AnjumSKhan

Reputation: 9827

Remove this , and use newButton in code below, and handle Loaded event :

    Grd.Children.Add(newButton);
    newButton.Loaded += newButton_Loaded;
    ...


void newButton_Loaded(object sender, RoutedEventArgs e)
        {
            Image img = (Image)newButton.Template.FindName("myimage", newButton);
            ...
        }

Upvotes: 1

Related Questions