WPF使用覆盖属性在XAML类继承 [英] WPF use override Property in inherit class in XAML

查看:594
本文介绍了WPF使用覆盖属性在XAML类继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题,不容找到任何解决方案。也许这是在Visual Studio中的一个问题。

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

我创建了一个从图片继承一个新的类。然后我重写Source属性。

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;
         } 
     }
}

如果我在代码中设置源

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



那么源将被正确设置为GifImage和消息框将显示。

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

但是,如果我在XAML的代码集来源:

But if I set Source in the Xaml-Code:

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



然后将图像的来源属性将设置并在MessageBox不需额外显示。

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

我的想法是设置System.ComponentModel.Browsable属性,认为也许在继承GifImage类的属性不是在Visual Studio中可见,它是使用source属性父类的。

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?

推荐答案

您无法在WPF的方式来覆盖的DependencyProperty。

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

作为图像源属性是一个的DependencyProperty,当值在XAML(和其他地方)被分配它的值用

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)

一个可能的解决方案是重写DependencyProperty的元数据,并添加更改侦听器,如:

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

或alternativly使用DependencyPropertyDescriptor

or alternativly using the DependencyPropertyDescriptor

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

这篇关于WPF使用覆盖属性在XAML类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆