【问题标题】:How to implement Dependency Property with inherited Control如何使用继承的控件实现依赖属性
【发布时间】:2022-12-17 07:58:37
【问题描述】:

我试图通过突出显示特定单词的行为来扩展 RichTextBox。我添加了 2 个属性,HighlightIndex 和 HighlightColor。对这些使用依赖属性,因此绑定效果很好。 问题是我不能同时继承 RichTextBox 和 DependencyObject -“类‘RichTextBoxHighlight’不能有多个基类:‘RichTextBox’和‘DependencyObject’。 如何实现依赖属性并仍然继承 RichTextBox?

    public partial class RichTextBoxHighlight : RichTextBox, DependencyObject
    {

        // Highlight Index
        public int HighlightIndex
        {
            get { return (int)GetValue(HighlightIndexProperty); }
            set { SetValue(HighlightIndexProperty, value); }
        }
        // Using a DependencyProperty as the backing store for HighlightIndex.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty HighlightIndexProperty = DependencyProperty.Register("HighlightIndex", typeof(int), typeof(RichTextBoxHighlight), 
                new PropertyMetadata(-1, new PropertyChangedCallback(HighlightIndex_PropertyChanged)));
        private static void HighlightIndex_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is not RichTextBoxHighlight r) return;
            r.SetHighlighting();
        }

        // Highlight Color
        public Color HighlightColor
        {
            get { return (Color)GetValue(HighlightColorProperty); }
            set { SetValue(HighlightColorProperty, value); }
        }

        // Using a DependencyProperty as the backing store for HighlightColor.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty HighlightColorProperty = DependencyProperty.Register("HighlightColor", typeof(Color), typeof(RichTextBoxHighlight), 
                new PropertyMetadata(Colors.Red, new PropertyChangedCallback(HighlightColor_PropertyChanged)));
        private static void HighlightColor_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is not RichTextBoxHighlight r) return;
            r.SetHighlighting();
        }

【问题讨论】:

  • RichTextBox 已经继承了 DependencyObject
  • @ASh - 如果我不继承 DependencyObject,则错误是 - 当前上下文中不存在名称“GetValue”
  • 我懂了。愚蠢的我。需要更改 RichTextBoxHighlight.g.i.cs 文件以继承 RichTextBox。谢谢,阿什。

标签: wpf dependencyobject


【解决方案1】:

我真傻。从 UserControl 开始,需要更改以继承 .xaml.cs 和 .g.i.cs 文件中的 RichTextBox。现在工作。 谢谢,ASh,让我看得更远。

【讨论】:

    猜你喜欢
    • 2013-04-01
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    相关资源
    最近更新 更多