是否可以重命名从另一个控件继承的自定义控件中的属性?

时间:2014-04-18 16:50:34

标签: wpf custom-controls

我想创建一个扩展Image并具有Source属性的自定义控件,该属性完全正常,但我想将其标记为Source以外的其他内容。这可能吗?

原因是我的自定义控件是ColorableImage,我希望OriginalSourceColoredSource都可以检索。我可以让控件的Source仅从ColoredSource拉出来,因为这是显示的内容,但后来我有两个属性做同样的事情。我也可以将名称保留为Source,但我认为这个名称在某种程度上有点令人困惑。

我还想过,也许我可以覆盖Source属性,只是通过使其无法设置来隐藏它,但似乎无法实现。

2 个答案:

答案 0 :(得分:1)

您可以创建一个不从Image而是从Image's基类下降的新类,并在内部使用Image实例。然后,您可以添加自己的ColoredSourceOriginalSource条款,然后影响内部Image实例的Source属性。就是这样:

public class ColoredImage : FrameworkElement {

    private Image Image { get; set; }

    public static readonly ColoredSourceProperty = DependencyProperty.Register( "ColoredSource", typeof( ImageSource ), typeof( ColoredImage ), new PropertyMetaData( null, new PropertyChangedCallback( OnColoredSourceChanged ) ) );

    public ColoredSource {
        get { return (ImageSource) GetValue( ColoredImageProperty ); }
        set { SetValue( ColoredImageProperty, value ); }
    }

    public ImageSource Originalsource {
        get { return Image.Source; }
        set { Image.Source = value; }
    }

    private static void OnColoredSourceChanged( DependencyObject d,
DependencyPropertyChangedEventArgs e ) {
        ColoredImage instance = d as ColoredImage;
        instance.Image.Source = e.NewValue as ImageSource;
    }

    // The rest of your logic here

}

答案 1 :(得分:0)

您可以设置“Base”等类,并设置公共或受保护的属性。

public string MyMessage { get; set; }

在基类的构造函数中实例化它。

然后创建另一个INHERITS这个类的类。就像'Dervied'一样,让它继承在顶层。

public class Derived : Base

如果它们是公共/受保护的,您现在可以获得基类的所有成员。您可以在基础中形成它们,然后始终设置它们。否则,您可以在派生类中形成它们。