简体   繁体   English

以编程方式更改按钮内的图像源

[英]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 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# 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! 非常感谢您的参与!

 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;

Eli was correct about removing the ContentTemplate. Eli关于删除ContentTemplate是正确的。 The following code is what achieved the image source change.. 以下代码实现了图像源更改。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM