【问题标题】:Displaying Default Image on Custom Control help? MSDN Tutorial在自定义控件帮助中显示默认图像? MSDN 教程
【发布时间】:2012-02-11 15:26:53
【问题描述】:

我正在 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));  
        }  
    }  


}

}

感谢您的帮助! =)

【问题讨论】:

  • 你有 images/Image.png 文件吗?
  • 是的,我愿意。我仔细检查了一遍。您认为这可能只是 Blend 4 上的一个错误吗?
  • 我会在构造函数中放置一个 try catch 并确保它正在获取图像。试试@"images/Image.png"。

标签: c# wpf xaml custom-controls blend


【解决方案1】:

当您声明 DependencyProperty 时,您可以为其指定默认值,如下所示:

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

DependencyProperty.Register 的最后一个参数是PropertyMetadata,您可以使用它来指定默认的ImageSource。 我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多