按名称访问ControlTemplate项目

时间:2014-10-16 07:13:32

标签: c# wpf

我有一个按钮:

<Button Name="btnPlayPause" HorizontalAlignment="Left" VerticalAlignment="Top" Height="30" Margin="8,10,0,0" Cursor="Hand" Click="btnPlayPause_Click">
    <Button.Template>
        <ControlTemplate>
            <Image Name="btnPlayPause_Image" Source="Images/Pause.png"/>
        </ControlTemplate>
    </Button.Template>
</Button>

我想在C#中更改Image(在ControlTemplate中)。我这样做:

//changing icon
BitmapImage iconPlay = new BitmapImage();
iconPlay.BeginInit();
iconPlay.UriSource = new Uri("images\\Play.png", UriKind.Relative);
iconPlay.EndInit();

btnPlayPause_Image.Source = iconPlay;

但我无法访问btnPlayPause_Image。它说它不存在于当前上下文中

但为什么??

当我创建没有ControlTemplate的按钮时:

<Button Name="btnPlayPause" HorizontalAlignment="Left" VerticalAlignment="Top" Height="30" Margin="8,10,0,0" Cursor="Hand" Click="btnPlayPause_Click">
    <Image Name="btnPlayPause_Image" Source="Images/Pause.png"/>
</Button>

C#代码工作正常。它找到btnPlayPause_Image并成功更改图像源:

1 个答案:

答案 0 :(得分:1)

Image不在窗口范围内。它位于Button模板的范围内。因此,您必须使用Button模板的FindName方法,如下所示:

var img = btnPlayPause.Template.FindName("btnPlayPause_Image", btnPlayPause) as Image;   //second parameter is the "ParentTemplate"
if(img != null) img.Source = iconPlay;