You can use Bindingto set the image. Therefore you must change ControlTemplate. In this example, we use the property Button Tagto set the 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 creating code Buttonshould 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;
source
share