WPF中通过点击按钮向Canvas添加TextBlock,该TextBlock在点击该控件后四周出现虚线边框,该边框可以通过拖动边框四周任意一条边动态改变边框大小以及边框内控件大小,在点击Canvas空白处消除掉该边框但保留边框内控件
时间: 2024-03-01 20:53:51 浏览: 96
wpf button去掉虚边框
4星 · 用户满意度95%
这个问题的实现可以分为以下几个步骤:
1. 创建一个Button控件,设置其点击事件为向Canvas添加TextBlock控件。
2. 在TextBlock控件的MouseDown事件中,创建一个矩形框并显示在TextBlock周围,同时设置该矩形框的鼠标事件,以便进行拖动和改变大小的操作。
3. 当矩形框被拖动或大小改变时,对应的TextBlock控件也需要相应地改变位置和大小。
4. 当Canvas空白处被点击时,需要判断当前是否存在矩形框,如果存在则将其隐藏并保留TextBlock控件。
下面是简单的代码示例,可供参考:
```
private void addButton_Click(object sender, RoutedEventArgs e)
{
TextBlock textBlock = new TextBlock();
textBlock.Text = "Hello World!";
// 设置TextBlock的MouseDown事件
textBlock.MouseDown += TextBlock_MouseDown;
canvas.Children.Add(textBlock);
}
private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
// 创建矩形框
Rectangle rect = new Rectangle();
rect.Stroke = Brushes.Black;
rect.StrokeDashArray = new DoubleCollection(new double[] { 1, 2 });
rect.Fill = Brushes.Transparent;
rect.Opacity = 0.5;
rect.MouseDown += Rect_MouseDown;
rect.MouseMove += Rect_MouseMove;
rect.MouseUp += Rect_MouseUp;
// 将矩形框显示在TextBlock周围
Point position = e.GetPosition(canvas);
Canvas.SetLeft(rect, position.X);
Canvas.SetTop(rect, position.Y);
rect.Width = textBlock.ActualWidth;
rect.Height = textBlock.ActualHeight;
canvas.Children.Add(rect);
// 将TextBlock控件移动到矩形框内部
Canvas.SetLeft(textBlock, position.X + 5);
Canvas.SetTop(textBlock, position.Y + 5);
}
private void Rect_MouseDown(object sender, MouseButtonEventArgs e)
{
isDragging = true;
lastPoint = e.GetPosition(canvas);
}
private void Rect_MouseMove(object sender, MouseEventArgs e)
{
if (isDragging)
{
Point currentPoint = e.GetPosition(canvas);
double offsetX = currentPoint.X - lastPoint.X;
double offsetY = currentPoint.Y - lastPoint.Y;
// 拖动矩形框
Canvas.SetLeft(rect, Canvas.GetLeft(rect) + offsetX);
Canvas.SetTop(rect, Canvas.GetTop(rect) + offsetY);
// 改变矩形框大小
rect.Width += offsetX;
rect.Height += offsetY;
// 改变TextBlock控件的位置和大小
Canvas.SetLeft(textBlock, Canvas.GetLeft(rect) + 5);
Canvas.SetTop(textBlock, Canvas.GetTop(rect) + 5);
textBlock.Width = rect.Width - 10;
textBlock.Height = rect.Height - 10;
lastPoint = currentPoint;
}
}
private void Rect_MouseUp(object sender, MouseButtonEventArgs e)
{
isDragging = false;
}
private void canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
// 判断是否存在矩形框
if (canvas.Children.Contains(rect))
{
// 隐藏矩形框
canvas.Children.Remove(rect);
// 将TextBlock控件移动到Canvas空白处
Point position = e.GetPosition(canvas);
Canvas.SetLeft(textBlock, position.X);
Canvas.SetTop(textBlock, position.Y);
}
}
```
阅读全文