JustLogin
JustLogin

Reputation: 1890

Extend WPF control class

I want to extend System.Windows.Controls.Image with some methods and variables. But as far as I know, WPF controls inheritance considered as a bad practice.

So, is creating a UserControl the only way? I really want to avoid this, because it makes element usage more complicated (for example, you have to call UserControl.Image.Source instead of Image.Source).

Are there any options?

Upvotes: 2

Views: 1679

Answers (2)

Andrea
Andrea

Reputation: 112

What about Extension Methods in a static class?

For Example:

public static class ExtensionMethods
{
    public static bool MyExtendedMethod(this System.Windows.Controls.Image source)
    {
        // do something
        return true;
    }
}

Upvotes: 1

ibebbs
ibebbs

Reputation: 1993

How about using attached properties and the associated PropertyChangedCallback methods to implement the functionality you desire. For example:

public class ImageProperties
{
    public static readonly DependencyProperty ByteEncodedStringProperty = DependencyProperty.RegisterAttached("ByteEncodedString", typeof(string), typeof(ImageProperties), new PropertyMetadata(null, ByteEncodedStringPropertyChanged));

    private static void ByteEncodedStringPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
    {
        Image image = sender as Image;

        if (image != null)
        {
            ImageSource imageSource = DecodeByteEncodedStringImage(args.NewValue);

            image.Source = imageSource;
        }
    }

    public static string GetByteEncodedString(DependencyObject obj)
    {
        return (string)obj.GetValue(ByteEncodedStringProperty);
    }

    public static void SetByteEncodedString(DependencyObject obj, string value)
    {
        obj.SetValue(ByteEncodedStringProperty, value);
    }
}

Upvotes: 0

Related Questions