WPF runtime image customization

I have a template in app.xaml. At run time, I want to create a button and apply this template. I also want to set the image source at 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);
+4
source share
2 answers

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;
+4
source

Remove thisand use newButtonin the code below and handle the 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);
            ...
        }
+1

Source: https://habr.com/ru/post/1620052/


All Articles