【问题标题】:WPF use override Property in inherit class in XAMLWPF 在 XAML 的继承类中使用覆盖属性
【发布时间】:2011-09-06 17:04:00
【问题描述】:

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

我创建了一个继承自 Image 的新类。然后我覆盖 Source 属性。

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

如果我在代码中设置 Source

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

然后Source将正确设置为GifImage并显示MessageBox。

但如果我在 Xaml-Code 中设置 Source:

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

然后会设置 Image 的 Source 属性,而 MessageBox 将不会显示。

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

[Browsable(true)]
public new ImageSource Source

但这仍然不起作用。

有人遇到过同样的问题或/和解决方案吗?

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    您无法在 WPF 中以这种方式覆盖 DependencyProperty。

    由于图像上的 Source 属性是一个 DependencyProperty,当在 XAML(和其他地方)中分配值时,它的值使用

    DependencyObject.SetValue(SourceProperty, value)
    

    一种可能的解决方案是覆盖 DependencyProperty 的元数据并添加更改侦听器,例如

        static GifImage()
        {
            SourceProperty.OverrideMetadata(typeof(GifImage), new FrameworkPropertyMetadata(new PropertyChangedCallback(SourcePropertyChanged)));
    
        }
    
        private static void SourcePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            MessageBox("new source property");
        }
    

    或交替使用 DependencyPropertyDescriptor

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

    【讨论】:

    • 对于第一个解决方案,我得到了一个 ArgumentException,即 PropertyMetadata 仍按“图像”类型注册
    • 我在 SourceProperty.OverrideMetadata(typeof(Image), new FrameworkPropertyMetadata(new PropertyChangedCallback(SourcePropertyChanged)));我必须使用我的控件的 typeof 来覆盖它。这里typeof(GifImage)
    • 太棒了,很高兴你成功了。我正要制作一个小应用程序来找出我做错了什么。我将更新答案以更改类型。
    猜你喜欢
    • 1970-01-01
    • 2013-12-04
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    相关资源
    最近更新 更多