2012-02-10 80 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。 我希望这可以帮助。

相关问题