如何在WPF中设置控件的边距?我曾经使用WinForms,我希望转换为WPF。
所以,我创建了一个新的WPF应用程序,从MainWindow中删除了Grid,添加了Canvas,并在Canvas上添加了两个Labels。我想在标签周围设置一个边距但是一旦我设置它,比如20,然后尝试移动它们以检查它是否有效,Label的Margin属性将值重置为0.我是否仍然可以在我可以在WinForms中使用WPF吗?
谢谢!
修改
希望这是感兴趣的代码。
因此,我在Property选项卡中更改Label的Margin值。看起来像这样:
<Window x:Class="WpfApplication1.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"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Canvas HorizontalAlignment="Left" Height="173" Margin="87,62,0,0" VerticalAlignment="Top" Width="205" Background="{DynamicResource {x:Static SystemColors.ControlBrushKey}}">
<Label x:Name="label" Content="Label" Canvas.Left="51" Canvas.Top="47" Margin="20"/>
<Label x:Name="label1" Content="Label" Canvas.Left="104" Canvas.Top="125" Margin="20"/>
</Canvas></Window>
然后,我拖动一个Label,它会自动更改为:
<Window x:Class="WpfApplication1.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"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Canvas HorizontalAlignment="Left" Height="173" Margin="87,62,0,0" VerticalAlignment="Top" Width="205" Background="{DynamicResource {x:Static SystemColors.ControlBrushKey}}">
<Label x:Name="label" Content="Label" Canvas.Left="51" Canvas.Top="47" Margin="20"/>
<Label x:Name="label1" Content="Label" Canvas.Left="129" Canvas.Top="101"/>
</Canvas> </Window>
如果我拖动另一个Label,它也会“重置”为零。
答案 0 :(得分:0)
看起来问题是当Label在Canvas中时。我添加了Grid的示例,它按预期工作,移动Label时重新计算Margin属性。
<Grid>
<Label x:Name="label1" Content="Label" Margin="20" VerticalAlignment="Top" Width="200"/>
</Grid>
或者,您可以使用Padding属性,如果这对您有用。无论你如何移动标签,它都会保持在20。
<Canvas HorizontalAlignment="Left" Height="173" Margin="87,62,0,0" VerticalAlignment="Top" Width="205" Background="{DynamicResource {x:Static SystemColors.ControlBrushKey}}">
<Label x:Name="label" Content="Label" Canvas.Top="40" Canvas.Left="21" Padding="20"/>
<Label x:Name="label1" Content="Label" Canvas.Left="32" Canvas.Top="125"/>
</Canvas>
但是,我强烈建议仅编辑源代码,不要触摸WPF Designer中的元素。您将获得对代码的更多控制权。