簡體   English   中英

將圖像添加到WPF C#中的按鈕,圖像不出現

[英]Adding image to a button in WPF C#, image not appearing

我想在Windows 8桌面應用程序中創建一個按鈕,該按鈕將具有圖像和文本塊。 我必須使用C#編碼來做到這一點。 我的代碼如下,

            Button btn = new Button();               
            StackPanel btnContentPanel = new StackPanel();
            btnContentPanel.Orientation = Orientation.Horizontal;

            Image img = new Image();
            img.Source = new BitmapImage(newUri(@"C:\Users\Desktop\Images\download.jpg"));
            img.Stretch = Stretch.Uniform;
            btnContentPanel.Children.Add(img);

            TextBlock txBlock = new TextBlock();
            txBlock.Text = "My Button";
            btnContentPanel.Children.Add(txBlock);               

            btn.Content = btnContentPanel;

這沒有給出任何錯誤,但是沒有顯示圖像。 如果我在圖像的位置添加了另一個文本塊,則該文本塊將出現,而不是圖像。

我有什么想念的嗎? 請幫忙,謝謝。

嘗試像這樣構建按鈕:

Button btn= new Button
{
    Width = 30,
    Height = 30,
    Content = new Image
    {
        Source = new BitmapImage(@"C:\Users\Desktop\Images\download.jpg"))
    }
};

對於“丟失”的圖像,需要考慮以下幾點:

當Xaml找不到資源時,它可能會忽略它(當它不會引發XamlParseException時)

必須正確添加和定義資源:

確保它在預期的項目中存在。

確保它與您的項目一起作為資源構建。

(右鍵單擊->屬性-> BuildAction ='Resource')

在此處輸入圖片說明

在類似情況下要嘗試的另一件事,這對於重新使用圖像(或任何其他資源)也很有用:

在Xaml中將圖像定義為資源:

<UserCondrol.Resources>
     <Image x:Key="MyImage" Source.../>
</UserControl.Resources>
And later use it in your desired control/controls:

<Button Content={StaticResource MyImage} />

暫無
暫無

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

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