Benjamin Pletcher
Benjamin Pletcher

Reputation: 33

Programmatically change Image Source inside of button

I am attempting to change the source of an image control inside of a button but am struggling to get it to work without an exception occuring. This is what I have so far

XAML

<Grid Height="33" VerticalAlignment="Top">
     <Button x:Name="btnAttendance" VerticalAlignment="Top" Height="33" BorderBrush="{x:Null}" Background="#FF1D2531" Foreground="#FFB7C0CD" FontSize="14" FontWeight="Bold" Padding="20,1,1,1" HorizontalContentAlignment="Left" Click="button_SidebarClick" Style="{StaticResource STY_SidebarPrimary}" FontFamily="Source Sans Pro Semibold">
          <Button.ContentTemplate>
               <DataTemplate>
                    <Grid>
                         <Image x:Name="imgAttendance" Source="Resources/IMG_LinkFull.png" Height="33" Width="Auto" Margin="23.5,0,0,0" VerticalAlignment="Top" HorizontalAlignment="Stretch" />
                         <TextBlock Margin="23,0,0,0" Width="Auto" FontFamily="Source Sans Pro Semibold" VerticalAlignment="Center" Foreground="#FF838990"><Run Text="Attendance"/></TextBlock>
                    </Grid>
               </DataTemplate>
          </Button.ContentTemplate>
     </Button>
</Grid>

C#

 ControlTemplate ct = btnAttendance.Template;
 Image btnImage = (Image)ct.FindName("imgAttendance", btnAttendance);
 btnImage.Source = new BitmapImage(new Uri("Resources/IMG_LinkFull_Active.png", UriKind.RelativeOrAbsolute));

Any idea where I am going wrong? I tried to reference the image file directly but the control is not visible/accessible.

Thank you so much for your time!

Upvotes: 0

Views: 825

Answers (2)

Benjamin Pletcher
Benjamin Pletcher

Reputation: 33

Eli was correct about removing the ContentTemplate. The following code is what achieved the image source change..

imgAttendance.Source = new BitmapImage(new Uri("Resources/IMG_LinkFull_Active.png", UriKind.RelativeOrAbsolute));

Upvotes: 0

Hardik Kothari
Hardik Kothari

Reputation: 1766

 ImageBrush myBrush = new ImageBrush();
                    Image image = new Image();
                    image.Source = new BitmapImage(new Uri(@"msappx:///Resources/IMG_LinkFull_Active.png"));
                    myBrush.ImageSource = image.Source;
                    btnAttendance.Background = myBrush;

Upvotes: 1

Related Questions