开发者

WPF Constrain the resize of a canvas' child object to the dimensions of the canvas

Given the following XAML:

<Window x:Class="AdornerTesting.Window1"
        xmlns="http://schemas.microsoft.com/开发者_运维知识库winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="500" Width="500"
        Loaded="Window_Loaded">
    <Grid Name="grid">
        <Canvas Name="canvas" Width="400" Height="400" Background="LightGoldenrodYellow">
            <RichTextBox Name="richTextBox" Canvas.Top="10" Canvas.Left="10" BorderBrush="Black" BorderThickness="2"
                     Width="200"
                     Height="200"
                     MaxWidth="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Canvas}},Path=ActualWidth}"
                     MaxHeight="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Canvas}},Path=ActualHeight}"/>
        </Canvas>
    </Grid>
</Window>

and a set of adorners being added to the RichTextBox in the Loaded event like so:

AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(richTextBox);
adornerLayer.Add(new ResizeAdorner(richTextBox));

How do I keep from being able to resize the RichTextBox beyond the visble bounds of the Canvas?

The ResizeAdorner is essentially the same code that can be found in the MSDN adorner example and it works just fine. Should I be doing something with the bindings of MaxWidth and MaxHeight in the code-behind to calculate how the RichTextBox can be resized? Or is there a way to do this in XAML?


If you are referring to the ResizingAdorner Sample on MSDN, then the code you posted is technically correct in that the RichTextBox will not be any larger than your canvas.

What you may be seeing is that as you resize the rich text box, the bottom and right sides will extend 10 pixels past the canvas bounds. This is because the XAML you posted says that the rich text box's MaxHeight and MaxWidth will be the height/width of the canvas.

The reason the rich text box extends 10 pixels beyond the canvas is because the rich text box is positioned at the Canvas.Top="10" and Canvas.Left="10" location of the canvas.

If you set the rich text box to be at Canvas.Top="0" Canvas.Left="0", then you'll see that the rich text box will never exceed the canvas bounds.

A couple of notes on the XAML and code behind...

Since you've a named canvas in your XAML, you don't need to a binding with a Find Ancestor, rather you can just use ElementName in your binding, i.e.,

<RichTextBox ...
   MaxWidth="{Binding ElementName=canvas,Path=ActualWidth}"
   MaxHeight="{Binding ElementName=canvas,Path=ActualHeight}"/>

In the code behind, the AdornerLayer should be your canvas, not the RichTextBox, i.e.,

AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(canvas);
adornerLayer.Add(new ResizeAdorner(richTextBox));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜