如何在网格中设置TextBlock的边界?

问题描述 投票:0回答:1

我在网格中有很少的文本块可以拖动。我想限制用户,以便用户无法在网格外拖动文本块。

我尝试了一些方法,比如获取网格的位置,以便我可以控制,但它没有按预期工作。提前致谢。

c# uwp grid uwp-xaml textblock
1个回答
1
投票

这可以很容易地使用Canvas内部的Grid,计算TextBlock内部的Canvas坐标,然后不断检查TextBlock是否仍在其范围内。当TextBlock离开它的边界时,Transform然后恢复到它最后已知的“好”坐标。

XAML

<Grid>
    <Grid Name="GridBounds" Width="600" Height="600" Background="Aqua">
        <Canvas>
            <TextBlock Name="TextBlock1" Text="Drag Me" FontSize="40" ManipulationDelta="TextBlock1_ManipulationDelta" ManipulationMode="TranslateX, TranslateY" HorizontalAlignment="Stretch" Canvas.Left="216" Canvas.Top="234" VerticalAlignment="Stretch"/>
        </Canvas>
    </Grid>
</Grid>

代码背后

    CompositeTransform TextDrag = new CompositeTransform();
    CompositeTransform savedTransform = new CompositeTransform();

    public MainPage()
    {          
        this.InitializeComponent();
        TextBlock1.RenderTransform = TextDrag;
    }

    // Copy Transform X and Y if TextBlock is within bounds
    private void CopyTransform(CompositeTransform orig, CompositeTransform copy)
    {
        copy.TranslateX = orig.TranslateX;
        copy.TranslateY = orig.TranslateY;
    }


    private void TextBlock1_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
    {
        TextDrag.TranslateX += e.Delta.Translation.X;
        TextDrag.TranslateY += e.Delta.Translation.Y;           

        CompositeTransform transform = TextBlock1.RenderTransform as CompositeTransform;

        // Get current Top-Left coordinates of TextBlock
        var TextTopLeft = TextBlock1.TransformToVisual(GridBounds).TransformPoint(new Point(0, 0));

        // Get current Bottom-Right coordinates of TextBlock
        var TextBottomRight = TextBlock1.TransformToVisual(GridBounds).TransformPoint(new Point(TextBlock1.ActualWidth, TextBlock1.ActualHeight));

        // Get Top-Left grid coordinates
        var GridTopLeft = (new Point(0, 0));

        // Get Bottom-Right grid coordinates
        var GridBottomRight = (new Point(GridBounds.ActualWidth, GridBounds.ActualHeight));

        if (TextTopLeft.X < GridTopLeft.X || TextBottomRight.X > GridBottomRight.X)
        {
            // Out of bounds on X axis - Revert to copied X transform
            TextDrag.TranslateX = savedTransform.TranslateX; ;
        }

        else if (TextTopLeft.Y < GridTopLeft.Y || TextBottomRight.Y > GridBottomRight.Y)
        {
            // Out of bounds on Y axis - Revert to copied Y transform
            TextDrag.TranslateY = savedTransform.TranslateY;
        }

        else
        {
            // TextBlock is within bounds - Copy X and Y Transform
            CopyTransform(transform, savedTransform);
        }
    }

这是在行动。 Here it is in action

© www.soinside.com 2019 - 2024. All rights reserved.