2012-02-10 44 views
0

我在MSDN上有關如何創建一個自定義控制在自定義控件幫助中顯示默認圖像? MSDN教程

http://msdn.microsoft.com/en-us/library/cc295235(v=expression.30).aspx

我有麻煩試圖在我的按鈕顯示的默認圖像做一個教程。

下面的代碼:

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.Windows.Shapes; 
using System.ComponentModel; 

namespace ControlTest 
{ 
/// <summary> 
/// Interaction logic for MainWindow.xaml 
/// </summary> 
public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     this.InitializeComponent(); 


    } 

} 
[Description("Represents a custom button control that responds to a Click event. Displays an image using a custom Source property if the Source property is bound to an Image in the template.")] 
public class ImageButton : Button 
{ 
    [Description("The image displayed in the button if there is an Image control in the template whose Source property is template-bound to the ImageButton Source property."), Category("Common Properties")] 
    public ImageSource Source 
    { 
     get { return base.GetValue(SourceProperty) as ImageSource; } 
     set { base.SetValue(SourceProperty, value); } 
    } 
    public static readonly DependencyProperty SourceProperty = 
     DependencyProperty.Register("Source", typeof(ImageSource), typeof(ImageButton)); 

    // Constructor: 
    public ImageButton() 
    { 
    if (DesignerProperties.GetIsInDesignMode(this)) 
    { 
     this.Source = new BitmapImage(new Uri("images/Image.png", UriKind.Relative)); 
     } 
    } 


} 

}

感謝您的幫助! =)

+0

你有一個images/Image.png文件嗎? – Paparazzi 2012-02-10 17:49:41

+0

是的,我願意。我再次檢查。你認爲它可能只是Blend 4的一個bug? – Farnsworth 2012-02-10 17:59:48

+0

我會在構造函數中放入一個try catch,並確保它正在獲取圖像。嘗試@「images/Image.png」。 – Paparazzi 2012-02-10 18:37:34

回答

0

在聲明DependencyProperty你可以爲它指定一個默認值,比如:

public static readonly DependencyProperty SourceProperty = 
      DependencyProperty.Register("Source", typeof (ImageSource), typeof (ImageButton), new PropertyMetadata("images/Image.png")); 

DependencyProperty.Register最後一個參數是一個PropertyMetadata你可以用它來指定一個默認ImageSource。 我希望這可以幫助。

相關問題