2012-06-19 53 views
2

我想在c#中創建一個沒有內容但僅包含圖像的按鈕。WPF安裝程序類

我不知道如何使用setter。任何人都可以啓發我嗎?

  Setter setter = new Setter(); 
      setter.Property = Image.SourceProperty; 
      setter.Value = "asd.jpg"; //<--error 

      Style Rstyle = new Style(); 
      Rstyle.TargetType = typeof(Button); 
      Rstyle.Setters.Add(setter); 

      Button _Button = new Button() 
      { 
       Width = 41, 
       Height = 41 
      }; 

      _Button.Style = Rstyle; 

要我穿什麼,在setter.Value獲得駐留在項目目錄中的圖像。 「asd.jpg」

回答

1

設置器不是在C#代碼中使用,它是一個輔助類來建立xamls風格。 只需使用此代碼即可。

BitmapImage bmp = new BitmapImage() 
bmp.BeginInit(); 
bmp.UriSource = new Uri("pack://application:,,,/ApplicationName;component/Resources/myImage.png"); 
bmp.EndInit(); 
Image image = new Image(); 
image.Source = bmp; 
myButton.Content = image; 
+0

啊,謝謝它的工作! – RStyle

+1

實際上,'Setter'用在觸發器和樣式中,無論是在C#中還是在XAML中。 – SLaks

+0

@SLaks當然你是對的,對於這個問題的問題,雖然他們沒有必要。 – dowhilefor

4

ButtonContent屬性,你可以轉儲BitmapImage它:

BitmapImage image = new BitmapImage(new Uri("your source")); 
TheButton.Content = image; 
+0

@RStyle你不需要。 BitmapImage本身就可以處理JPEG。 – vcsjones

+0

嘿爲什麼圖片只顯示,如果我通過下面列出的方法回答「dowhilefor」。創建bitmapimage後,我們需要使用Image類,然後將其分配給內容。 – RStyle

0
<ControlTemplate x:Key="image"> //XAML in window resources tag 
      <Image Source="Save.png"/> 
    </ControlTemplate> 


btn.Template = (ControlTemplate)FindResource("image"); 

我覺得這是更靈活的和可重複使用。