简体   繁体   English

wpf无法在隐藏代码中更改图像的来源

[英]wpf can't change the source of a image in Code Behind

I am currently working a new project and I need to change the source of a image in my WPF project, but when I'm going into the Code Behind, it can't find the name in the context. 我目前正在一个新项目中,需要在WPF项目中更改图像的来源,但是当我进入“代码隐藏”时,它无法在上下文中找到名称。 Here my code : 这是我的代码:

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

Try this to get Image control from code : 尝试此操作以从代码获取Image控件:

var template = mediaControlButton.Template;
var imageControl = (Image)template.FindName("iconPlaying", mediaControlButton);

here is an alternative to attempting to modify the template in the code behind. 这是尝试修改后面代码中的模板的替代方法。 with this, you wont be modifying the template but the content of the button (which should really be independent of the control template anyway) 这样,您将不会修改模板,但可以修改按钮的内容(无论如何,它实际上应该独立于控件模板)

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

this way, whatever you throw in the Button.Content property will be set in the ContentControl of the ControlTemplate 这样,您在Button.Content属性中抛出的任何内容都将在ControlTemplateContentControl中进行设置

In the code behind you can get the image like this: 在后面的代码中,您可以得到如下图像:

var iconplaying = (mediaControlButton.Content as System.Windows.Controls.Image);
iconplaying.Source = "whatever.png";

If the control template for this button is going to be used in more than one place, you should define it as a Style 如果此按钮的控件模板要在多个地方使用,则应将其定义为“样式”

try: 尝试:

var iconplaying = (mediaControlButton.Content as System.Windows.Controls.Image);    
iconplaying.Source = "theimage.png"

and bind it to the image in the xaml 并将其绑定到xaml中的图像

also have a look at this post 也看看这个帖子

WPF Image Dynamically changing Image source during runtime WPF图像在运行时动态更改图像源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM