我目前正在开发一个新项目,我需要在WPF项目中更改图像的来源,但是当我进入Code Behind时,它无法在上下文中找到该名称。这是我的代码:
<Button x:Name="mediaControlButton" Width="20" Height="20" Margin="161,54,219,26">
<Button.Template>
<ControlTemplate>
<Border HorizontalAlignment="Center" VerticalAlignment="Center" >
// This is the image I need to change the source wich the Code Behing can't find.
<Image x:Name="iconPlaying" Source="Resources/play.png"
Width="20"
Height="20"/>
</Border>
</ControlTemplate>
</Button.Template>
</Button>
答案 0 :(得分:1)
尝试通过代码获取Image
控件:
var template = mediaControlButton.Template;
var imageControl = (Image)template.FindName("iconPlaying", mediaControlButton);
答案 1 :(得分:0)
这是尝试修改后面代码中的模板的替代方法。有了这个,你不会修改模板,而是修改按钮的内容(无论如何它应该真的独立于控件模板)
<Button x:Name="mediaControlButton" Width="20" Height="20" >
<Button.Template>
<ControlTemplate TargetType="Button">
<Border HorizontalAlignment="Center" VerticalAlignment="Center" BorderBrush="Red" BorderThickness="2" >
<ContentControl Content="{TemplateBinding Content}"/>
</Border>
</ControlTemplate>
</Button.Template>
<Image x:Name="buttonImage" Source="Resources/left.jpg"
Width="20"
Height="20"/>
</Button>
这样,无论你在Button.Content
属性中抛出什么,都会在ContentControl
ControlTemplate
中设置
在后面的代码中你可以得到这样的图像:
var iconplaying = (mediaControlButton.Content as System.Windows.Controls.Image);
iconplaying.Source = "whatever.png";
如果此按钮的控件模板将在多个位置使用,则应将其定义为样式
答案 2 :(得分:0)
尝试:
var iconplaying = (mediaControlButton.Content as System.Windows.Controls.Image);
iconplaying.Source = "theimage.png"
并将其绑定到xaml中的图像
也看一下这篇文章