【问题标题】:How to define a custom Rectangle class driven from the Rectangle class?如何定义从 Rectangle 类驱动的自定义 Rectangle 类?
【发布时间】:2013-05-06 18:09:21
【问题描述】:

我已经在 WPF 中编写了一个定制的 RichTextBox 类。但我需要在此RichTextBox 的左上角有一个小矩形,以便在我想拖动RichTextBox 时将其用作拖动手柄。
所以我是这样开始的:

public class DragHandleRegtangle : Shape
    {
        public double len = 5;
        public double wid = 5;

        public DragHandleRegtangle()
        {
           //what should be here exactly, anyway? 
        }
    }
//Here goes my custom RichTextBox
public class CustomRichTextBox : RichTextBox
...

但我不知道如何指定它的宽度/长度/填充颜色,最重要的是它与RichTextBox 相关的位置(这与 RichTextBox 的锚点完全零零相关 - 即:顶部它的左角)

到目前为止,我遇到的第一个错误是:

'ResizableRichTextBox.DragHandleRegtangle' 没有实现 继承的抽象成员 'System.Windows.Shapes.Shape.DefiningGeometry.get'

如果有人能帮我定义我的矩形并解决此错误,我将不胜感激。

【问题讨论】:

    标签: wpf derived-class rectangles


    【解决方案1】:

    将此写入您的代码

       protected override System.Windows.Media.Geometry DefiningGeometry
       {
          //your code
       }
    

    【讨论】:

    • 非常感谢!在您编写的代码中,我有这个:get { throw new NotImplementedException(); } 它解决了错误,但我仍然没有画布中的矩形!我的意思是它没有渲染或其他东西。以及如何设置此 Rectangle 的宽度/高度/bg 颜色等?
    • 我从未继承过 UI 控件,因此无法进一步帮助您。但是,当您需要一个 Rectangle 时,为什么不使用 Rectangle 类呢?
    【解决方案2】:

    WPF 框架有一个类可以满足您的需求。 Thumb 类表示允许用户拖动和调整控件大小的控件。通常在制作自定义控件时使用。 MSDN Docs for Thumb class

    以下是如何实例化拇指并连接一些拖动处理程序。

    private void SetupThumb () {
      // the Thumb ...represents a control that lets the user drag and resize controls."
      var t = new Thumb();
      t.Width = t.Height = 20;
      t.DragStarted += new DragStartedEventHandler(ThumbDragStarted);
      t.DragCompleted += new DragCompletedEventHandler(ThumbDragCompleted);
      t.DragDelta += new DragDeltaEventHandler(t_DragDelta);
      Canvas.SetLeft(t, 0);
      Canvas.SetTop(t, 0);
      mainCanvas.Children.Add(t);
    }
    
    private void ThumbDragStarted(object sender, DragStartedEventArgs e)
    {
      Thumb t = (Thumb)sender;
      t.Cursor = Cursors.Hand;
    }
    
    private void ThumbDragCompleted(object sender,      DragCompletedEventArgs e)
    {
      Thumb t = (Thumb)sender;
      t.Cursor = null;
    }
    void t_DragDelta(object sender, DragDeltaEventArgs e)
    {
      var item = sender as Thumb;
    
      if (item != null)
      {
        double left = Canvas.GetLeft(item);
        double top = Canvas.GetTop(item);
    
        Canvas.SetLeft(item, left + e.HorizontalChange);
        Canvas.SetTop(item, top + e.VerticalChange);
      }
    
    }
    

    【讨论】:

    • 非常感谢!我很快就会测试它;)
    猜你喜欢
    • 2022-06-13
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    相关资源
    最近更新 更多