我的WPF应用程序中有这个图像按钮:
<Button Grid.Column="2" Content="Play" Focusable="False" Width="100" Height="60" HorizontalAlignment="Left" VerticalAlignment="Center" Name="PlayPauseButton" Click="PlayPauseButton_Click">
<Button.Template>
<ControlTemplate>
<Image x:Name="PlayPauseImage" Visibility="Visible" Stretch="Uniform" Source="/PlayTube;component/images/PlayerApplication/PlayButton.png" />
</ControlTemplate>
</Button.Template>
</Button>
我希望能够以编程方式设置Image
,但我无法访问PlayPauseImage
。
知道为什么会这样吗?
答案 0 :(得分:2)
您可以使用FrameworkTemplate.FindName
在ControlTemplate
var img = PlayPauseButton.Template.FindName("PlayPauseImage", PlayPauseButton) as Image;
答案 1 :(得分:1)
尝试使用FindName
:
private void PlayPauseButton_Click(object sender, RoutedEventArgs e)
{
Image image = (Image)PlayPauseButton.Template.FindName("PlayPauseImage", PlayPauseButton);
}
Note:
只有在控件完全加载时才使用FindName
,否则它将找不到它并给出null。
此活动也有:
答案 2 :(得分:0)
确保Button
为Loaded
..所以最好使用Loaded
事件来获取此内容...
private void ButtonBase_Loaded(object sender, EventArgs e)
{
var image = PlayPauseButton.Template.FindName("PlayPauseImage", PlayPauseButton) as Image;
}