簡體   English   中英

wpf無法在隱藏代碼中更改圖像的來源

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

我目前正在一個新項目中,需要在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>

嘗試此操作以從代碼獲取Image控件:

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

這是嘗試修改后面代碼中的模板的替代方法。 這樣,您將不會修改模板,但可以修改按鈕的內容(無論如何,它實際上應該獨立於控件模板)

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

如果此按鈕的控件模板要在多個地方使用,則應將其定義為“樣式”

嘗試:

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

並將其綁定到xaml中的圖像

也看看這個帖子

WPF圖像在運行時動態更改圖像源

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM