gpt4 book ai didi

wpf - Window.Margin 和 Window.Padding 不起作用

转载 作者:行者123 更新时间:2023-12-02 08:09:04 25 4
gpt4 key购买 nike

我正在设置窗口的属性 Margin 和 Padding,但它没有生效:

这是一个例子:

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
SizeToContent="WidthAndHeight"
ResizeMode="NoResize"
Padding="22"
Margin="22">

<Grid>
<Label
FontWeight="Bold"
FontSize="36"
BorderThickness="1"
BorderBrush="Red"
Content="Hello world!"/>
</Grid>
</Window>

结果:
alt text

期望的结果是标签的红框应距窗口框架 44 像素(边距+内边距)。

是的,我知道我可以设置标签的边距,但这不是我想要的。我有一个整个项目,它的所有窗口都设置为一种样式,我想在常规窗口样式中设置此属性(或其他属性)。

我想如果我找不到任何解决方案,我将创建一个贪婪的命名样式,在其中设置边距/填充,然后我将逐个窗口并设置网格的样式,但这是我想要的最后一个选项做。
提前致谢。

最佳答案

边距不起作用并不奇怪,因为边距是控件周围放置的空间量。对于 Window,这意味着使框架更小(和偏移),而不是客户区域,这会有点奇怪(并且可能无法与 Win32 托管环境很好地配合,不确定)。填充不起作用有点令人惊讶,我不确定为什么会这样。

但是,有一种解决方法可以封装在样式中:将默认的 Window ControlTemplate 替换为您自己的符合 Padding 的模板:

<ControlTemplate TargetType="Window">
<Border Background="White" Padding="{TemplateBinding Padding}">
<ContentPresenter />
</Border>
</ControlTemplate>

(您可能希望边框背景成为生产代码的动态窗口背景画笔,但您明白了。)

显然,您可以将此模板放入样式模板 setter 中,以避免在每个窗口上重复它。

这是完整的模板(使用 Microsoft Expression 生成):

<Style x:Key="WindowStyle" TargetType="{x:Type Window}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Window}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Margin="{TemplateBinding Margin}"
Padding="{TemplateBinding Padding}">

<AdornerDecorator>
<ContentPresenter/>
</AdornerDecorator>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="ResizeMode" Value="CanResizeWithGrip">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Window}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">

<Grid>
<AdornerDecorator>
<ContentPresenter/>
</AdornerDecorator>
<ResizeGrip
x:Name="WindowResizeGrip"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
IsTabStop="false"
Visibility="Collapsed"
/>
</Grid>
</Border>
<ControlTemplate.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition
Property="ResizeMode"
Value="CanResizeWithGrip"
/>
<Condition
Property="WindowState"
Value="Normal"
/>
</MultiTrigger.Conditions>
<Setter
Property="Visibility"
TargetName="WindowResizeGrip"
Value="Visible"/>
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>

关于wpf - Window.Margin 和 Window.Padding 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1993671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com