WPF中DockPanel内设置靠右停靠的Canvas反而居中是什么原因?
问题原因
你遇到的问题是DockPanel的LastChildFill属性默认逻辑导致的:
- 当
LastChildFill设置为True时,DockPanel会忽略最后一个子元素的DockPanel.Dock附加属性,强制将其拉伸填充DockPanel的全部剩余空间 - 你当前的DockPanel内只有Canvas一个子元素,它会被判定为最后一个子元素,因此你设置的
DockPanel.Dock="Right"不会生效 - 由于你给Canvas显式指定了
Width="100",Canvas不会被拉伸到满宽,会默认居中显示在被分配的满屏空间内,最终就出现了你看到的居中效果。
解决方案
你可以根据需求选择任意一种修复方式:
方案1:关闭LastChildFill
直接将DockPanel的LastChildFill改为False即可让Canvas的停靠属性生效:
<Window x:Class="Foo.Bar.MainWindow" 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" mc:Ignorable="d" Title="MainWindow" Height="400" Width="400"> <DockPanel LastChildFill="False"> <!-- 可自行添加Background属性方便验证停靠效果 --> <Canvas DockPanel.Dock="Right" Width="100" /> </DockPanel> </Window>
方案2:额外添加最后一个填充元素
如果你需要保留LastChildFill="True"的逻辑,只需要在Canvas之后添加一个新的子元素作为最后一个填充项即可:
<Window x:Class="Foo.Bar.MainWindow" 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" mc:Ignorable="d" Title="MainWindow" Height="400" Width="400"> <DockPanel LastChildFill="True"> <Canvas DockPanel.Dock="Right" Width="100" /> <!-- 新增最后一个子元素,将自动填充剩余空间 --> <Grid /> </DockPanel> </Window>
内容的提问来源于stack exchange,提问作者Anders Lindén
相关产品推荐
相关产品推荐

