-1
我想在容器內繪製區域。爲此我想到了使用自定義控件。WPF在容器中繪製邊框
我的問題是,畫布不佔用所有給定的空間。如何強行使用使用所有可用空間?
我所做的是從畫布繼承和創建邊框元素裏面:
public class DrawableCanvas : Canvas
{
private Border border;
static DrawableCanvas()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(DrawableCanvas), new FrameworkPropertyMetadata(typeof(DrawableCanvas)));
}
public DrawableCanvas()
{
this.border = new Border();
border.Background = new SolidColorBrush(Colors.Blue);
border.BorderThickness = new Thickness(1);
border.Width = 0;
border.Visibility = Visibility.Hidden;
border.Opacity = 0.3;
this.Children.Add(border);
this.MouseLeftButtonDown += DrawableCanvas_MouseLeftButtonDown;
this.MouseLeftButtonUp += DrawableCanvas_MouseLeftButtonUp;
this.MouseMove += DrawableCanvas_MouseMove;
}
private void DrawableCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Debug.WriteLine("Left mouse up");
// release mouse
Mouse.Capture(null);
border.Width = 0;
border.Height = 100;
startPosition = 0;
}
double startPosition = 0;
private void DrawableCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Debug.WriteLine("Left mouse down");
border.Visibility = Visibility.Visible;
// capture mouse
Mouse.Capture(this);
var point = e.GetPosition(this);
startPosition = point.X;
SetLeft(border, point.X);
}
private void DrawableCanvas_MouseMove(object sender, MouseEventArgs e)
{
if(this.IsMouseCaptured)
{
var point = e.GetPosition(this);
Debug.WriteLine("Mouse move");
// set the position to far left
SetLeft(border, Math.Min(startPosition, point.X));
// width is the difference between two points
border.Width = Math.Abs(startPosition - point.X);
Debug.WriteLine(Math.Min(startPosition, point.X));
Debug.WriteLine(border.Width);
}
}
}
,爲View:
<DockPanel>
<local:DrawableCanvas>
<Rectangle Height="500" Width="500" Fill="Transparent" />
</local:DrawableCanvas>
</DockPanel>
你確定DockPanel延伸到所有空間嗎?提供更多的XAML。 –
我在一個窗口中的Grid中使用了DockPanel的代碼。我做的唯一改變是''。 'DockPanel'填充'Grid'和'Grid'填充窗口。請解釋您爲什麼認爲自己有問題。你是否因爲「Border」高度始終爲100而感到困惑?那是因爲你把它設置爲那個,並且永遠不要改變它。 –
嘗試刪除矩形元素。在這種情況下,鼠標事件不會被觸發。 我剛剛發現,當我設置背景畫布透明這個作品。你能解釋爲什麼我會接受你的回答:) –