没有按要求在点击文字控件后添加对用边框,且是通过拖动边框来改变边框大小和边框内控件大小
时间: 2024-03-01 21:52:47 浏览: 71
非常抱歉,并未完全理解您的需求。如果您需要在点击文字控件后添加对应边框,并通过拖动边框来改变边框大小和边框内控件大小,可以参考以下代码实现:
首先,在XAML中添加一个Canvas和一个按钮:
```xml
<Grid>
<Canvas x:Name="canvas" Background="White" MouseDown="Canvas_MouseDown" MouseMove="Canvas_MouseMove" MouseUp="Canvas_MouseUp"/>
<Button x:Name="addButton" Content="Add TextBlock" Click="addButton_Click"/>
</Grid>
```
在按钮的Click事件处理程序中,创建一个边框控件和一个TextBlock控件,并将其添加到Canvas中:
```csharp
private void addButton_Click(object sender, RoutedEventArgs e)
{
TextBlock textBlock = new TextBlock();
textBlock.Text = "Click me!";
textBlock.FontSize = 16;
textBlock.Background = Brushes.LightGray;
textBlock.Padding = new Thickness(10);
textBlock.Cursor = Cursors.Hand;
Border border = new Border();
border.BorderThickness = new Thickness(1);
border.BorderBrush = Brushes.Black;
border.Child = textBlock;
// 设置边框的大小和位置,并添加到Canvas中
border.Width = 120;
border.Height = 60;
Canvas.SetLeft(border, 100);
Canvas.SetTop(border, 100);
canvas.Children.Add(border);
// 添加鼠标事件
border.PreviewMouseDown += new MouseButtonEventHandler(Border_PreviewMouseDown);
border.PreviewMouseMove += new MouseEventHandler(Border_PreviewMouseMove);
border.PreviewMouseUp += new MouseButtonEventHandler(Border_PreviewMouseUp);
}
```
在边框控件的PreviewMouseDown事件处理程序中,记录鼠标位置和边框位置,并将isDragging设置为true:
```csharp
double lastX, lastY;
double lastWidth, lastHeight;
double lastLeft, lastTop;
bool isDragging = false;
Border selectedBorder;
private void Border_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
// 记录鼠标位置和边框位置
lastX = e.GetPosition(canvas).X;
lastY = e.GetPosition(canvas).Y;
selectedBorder = (Border)sender;
lastWidth = selectedBorder.Width;
lastHeight = selectedBorder.Height;
lastLeft = Canvas.GetLeft(selectedBorder);
lastTop = Canvas.GetTop(selectedBorder);
isDragging = true;
// 将边框置于最前面
selectedBorder.SetValue(Canvas.ZIndexProperty, canvas.Children.Count);
}
```
在边框控件的PreviewMouseMove事件处理程序中,计算鼠标移动的距离,并根据移动的距离改变边框的大小和位置:
```csharp
private void Border_PreviewMouseMove(object sender, MouseEventArgs e)
{
if (isDragging)
{
// 计算鼠标移动的距离
double deltaX = e.GetPosition(canvas).X - lastX;
double deltaY = e.GetPosition(canvas).Y - lastY;
// 改变边框的大小和位置
double newWidth = lastWidth + deltaX;
double newHeight = lastHeight + deltaY;
if (newWidth > 0 && newHeight > 0)
{
selectedBorder.Width = newWidth;
selectedBorder.Height = newHeight;
Canvas.SetLeft(selectedBorder, lastLeft + deltaX);
Canvas.SetTop(selectedBorder, lastTop + deltaY);
}
}
}
```
在边框控件的PreviewMouseUp事件处理程序中,释放鼠标,完成边框移动改变大小的操作:
```csharp
private void Border_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
isDragging = false;
}
```
这样,当用户点击按钮时,会在Canvas上添加一个包含TextBlock的边框。当用户点击边框时,会出现边框,并可以通过拖动边框来改变边框大小和边框内控件大小。
阅读全文