Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# WPF约束画布的大小';将子对象添加到画布的维度_C#_Wpf_Xaml - Fatal编程技术网

C# WPF约束画布的大小';将子对象添加到画布的维度

C# WPF约束画布的大小';将子对象添加到画布的维度,c#,wpf,xaml,C#,Wpf,Xaml,给定以下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" Lo

给定以下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>
我如何防止RichTextBox的大小超出画布的可视范围


ResizeAdorner本质上与MSDN adorner示例中的代码相同,并且工作正常。我是否应该在代码中使用MaxWidth和MaxHeight的绑定来计算RichTextBox的大小?或者在XAML中是否有这样做的方法?

如果您指的是,那么您发布的代码在技术上是正确的,因为RichTextBox不会比画布大

您可能会看到,当您调整富文本框的大小时,底部和右侧将超出画布边界10像素。这是因为您发布的XAML指出,富文本框的MaxHeight和MaxWidth将是画布的高度/宽度

富文本框超出画布10像素的原因是富文本框位于画布的canvas.Top=“10”和canvas.Left=“10”位置

如果将富格文本框设置为位于Canvas.Top=“0”Canvas.Left=“0”,则您将看到富格文本框永远不会超出画布边界

关于XAML和代码隐藏的几个注意事项

因为在XAML中有一个命名画布,所以不需要使用Find祖先绑定,只需在绑定中使用ElementName即可,即

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

是的,将控件的初始位置更改为画布上的0,0将修复拖动到画布边缘右侧和底部的问题。我所遇到的问题,以及我在最初的问题中没有提到的问题,是向左和向上调整大小。不知道我怎么没有在最初的问题中提到,但我没有。结果是我在这些方向上调整代码的大小才是罪魁祸首。感谢关于XAML绑定的提示,绑定的东西有时还是会让我感到困惑。
<RichTextBox ...
   MaxWidth="{Binding ElementName=canvas,Path=ActualWidth}"
   MaxHeight="{Binding ElementName=canvas,Path=ActualHeight}"/>
AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(canvas);
adornerLayer.Add(new ResizeAdorner(richTextBox));