简体   繁体   中英

WPF use override Property in inherit class in XAML

I have a little problem and can´t find any solution. Maybe it is an issue in Visual Studio.

I have created a new class that is inherited from Image. I then override the Source property.

class GifImage : Image
{
     public new ImageSource Source
     {
         get { return base.Source; } 
         set
         {
             MesssageBox("new source property");
             base.Source = value;
         } 
     }
}

If I set Source in code

GifImage gifImage = new GifImage();
gifImage.Source = gifimage2;

Then the Source will be correctly set to GifImage and the MessageBox will be shown.

But if I set Source in the Xaml-Code:

<my1:GifImage Stretch="Uniform" Source="/WpfApplication1;component/Images/Preloader.gif" />

Then the Source property of the Image will be set and the MessageBox won´t be shown.

My idea was to set the System.ComponentModel.Browsable-Attribute, thinking that maybe the property in the inherit GifImage class is not visible in Visual Studio and it is using the source property of the parent class.

[Browsable(true)]
public new ImageSource Source

But this is still not working.

Has somebody had the same problem or/and the solution for this?

You are not able to override a DependencyProperty in that manner in WPF.

As the Source property on an Image is a DependencyProperty, when the value is assigned in XAML (and other places) it's value is set using

DependencyObject.SetValue(SourceProperty, value)

One possible solution is to override the metadata of the DependencyProperty and add change listener, eg

    static GifImage()
    {
        SourceProperty.OverrideMetadata(typeof(GifImage), new FrameworkPropertyMetadata(new PropertyChangedCallback(SourcePropertyChanged)));

    }

    private static void SourcePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
    {
        MessageBox("new source property");
    }

or alternativly using the DependencyPropertyDescriptor

DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(Image.SourceProperty, typeof(Image));
if (dpd != null)
{
   dpd.AddValueChanged(tb, delegate
   {
       MessageBox("new source property");
   });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM