我正在尝试更改按钮内部的图像控件的来源,但我正在努力让它工作而不会发生异常。这就是我到目前为止所拥有的
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));
知道我哪里错了吗?我试图直接引用图像文件,但控件不可见/无法访问。
非常感谢您的时间!
答案 0 :(得分:0)
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;
答案 1 :(得分:0)
Eli对删除ContentTemplate是正确的。以下代码是实现图像源更改的原因。
imgAttendance.Source = new BitmapImage(new Uri("Resources/IMG_LinkFull_Active.png", UriKind.RelativeOrAbsolute));