【问题标题】:wpf can't change the source of a image in Code Behindwpf 无法更改代码隐藏中的图像来源
【发布时间】:2014-01-03 02:23:50
【问题描述】:

我目前正在处理一个新项目,我需要在我的 WPF 项目中更改图像的来源,但是当我进入代码隐藏时,它在上下文中找不到名称。这是我的代码:

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

【问题讨论】:

标签: c# wpf


【解决方案1】:

试试这个从代码中获取Image控制:

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

【讨论】:

    【解决方案2】:

    这里是尝试在后面的代码中修改模板的替代方法。这样,您将不会修改模板,而是修改按钮的内容(无论如何,它应该真正独立于控件模板)

    <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 属性中输入的任何内容都将设置在ControlTemplateContentControl

    在后面的代码中你可以得到这样的图像:

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

    如果此按钮的控件模板将在多个地方使用,则应将其定义为样式

    【讨论】:

      【解决方案3】:

      尝试:

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

      并将其绑定到 xaml 中的图像

      也可以看看这篇文章

      WPF Image Dynamically changing Image source during runtime

      【讨论】:

        猜你喜欢
        • 2012-05-30
        • 1970-01-01
        • 1970-01-01
        • 2010-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-10
        相关资源
        最近更新 更多