用鼠标移动时WPF剪裁边框

时间:2015-01-11 14:23:18

标签: c# wpf

我正在尝试使用一些允许使用鼠标移动UIElement的代码。 除非被拖动的UI元素从其包含窗口的底部或右侧移动到其高度或宽度内,否则它将被裁剪。在改变被拖动的UIElement的大小之后,显然裁剪区域与相对于右侧或底部的宽度或高度成比例。

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    x:Class="MainWindow"
    mc:Ignorable="d"
    Title="" Height="500" Width="500" MaxWidth="500" MaxHeight="500">
    <Grid>
       <Border BorderBrush="Black" 
            MouseLeftButtonDown="UIElement_OnMouseLeftButtonDown"
            MouseLeftButtonUp="UIElement_OnMouseLeftButtonUp"
            MouseMove="UIElement_OnMouseMove" BorderThickness="1" Background="#FFDE1B1B"            
            VerticalAlignment="Top" HorizontalAlignment="Left" Width="100" Height="100"    
            Margin="84,82,0,0"/>
    </Grid>
</Window>

public partial class MainWindow : Window
{
    private bool moving = false;
    Point _previous = new Point();

    public MainWindow()
    {
        InitializeComponent();
    }

    private void UIElement_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        var l = e.Source as UIElement;
        if (l != null && l.IsMouseDirectlyOver)
        {
            _previous = e.GetPosition(null);
            l.CaptureMouse();
            moving = true;
        }
    }

    private void UIElement_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        Console.WriteLine(this.Width + ", " + this.Height);

        var l = e.Source as UIElement;
        if (l != null)
        {
            l.ReleaseMouseCapture();
            moving = false;
        }
    }

    private void UIElement_OnMouseMove(object sender, MouseEventArgs e)
    {
        if (moving)
        {
            var p = e.GetPosition(null);

            if (_previous != default(Point))
            {
                var ui = sender as FrameworkElement;

                var deltaX = p.X - _previous.X;
                var deltaY = p.Y - _previous.Y;

                ui.Margin = new Thickness(
                    Math.Max(ui.Margin.Left + deltaX, 0),
                    Math.Max(ui.Margin.Top + deltaY, 0),
                    ui.Width,
                    ui.Height);

                Title = ui.Margin.ToString();
            }
            _previous = p;
        }
    }
}

目前不知道为什么要修剪边框。

1 个答案:

答案 0 :(得分:0)

因为您专门将右边缘的边距设置为ui.Width,并将底边的边距设置为ui.Height。将它们都设置为0(默认值),并且不剪切元素。

ui.Margin = new Thickness(
                Math.Max(ui.Margin.Left + deltaX, 0),
                Math.Max(ui.Margin.Top + deltaY, 0),
                0, //ui.Width,
                0); //ui.Height);