在ControlTemplate中设置按钮图像

时间:2014-02-05 10:23:00

标签: c# wpf image button controltemplate

我的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

知道为什么会这样吗?

3 个答案:

答案 0 :(得分:2)

您可以使用FrameworkTemplate.FindNameControlTemplate

中找到控件
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。

此活动也有:

ContentRendered for Window

Loaded

答案 2 :(得分:0)

确保ButtonLoaded ..所以最好使用Loaded事件来获取此内容...

private void ButtonBase_Loaded(object sender, EventArgs e)
{
    var image = PlayPauseButton.Template.FindName("PlayPauseImage", PlayPauseButton) as Image;
}