开发者

WPF use override Property in inherit class in XAML

开发者 https://www.devze.com 2023-04-02 22:41 出处:网络
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.

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 pr开发者_运维技巧operty");
             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, e.g.

    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");
   });
}
0

精彩评论

暂无评论...
验证码 换一张
取 消