首页 > 解决方案 > WPF:无法正确设置边距

问题描述

我尝试制作一个简单的地图应用程序。当我在此地图上放置一些图钉(标记)并使用边距调整它们的位置时,它们无法正确显示。这是我的代码:

标记.xaml:

<UserControl
x:Class="GothicMapViewer.Marker"
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:local="clr-namespace:GothicMapViewer"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DesignHeight="15"
d:DesignWidth="15"
mc:Ignorable="d">

<Grid>
    <Ellipse
        Name="MarkerPoint"
        Width="15"
        Height="15"
        HorizontalAlignment="Left"
        VerticalAlignment="Top"
        Fill="#FFF4F4F5"
        Stroke="Black" />
</Grid>

MapViewModel.cs:

private void SetMarkerData(MapType mapType)
    {
        var markersData = mapRepository.GetMarkers(mapType);

        foreach (var item in markersData.Herbs)
        {
            Markers.Add(new MarkerViewModel()
            {
                Margin = new Thickness(item.PositionX, item.PositionY, 0, 0),
            });
        }
    }

地图.xaml:

<UserControl
x:Class="GothicMapViewer.Map"
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:local="clr-namespace:GothicMapViewer"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DesignHeight="750"
d:DesignWidth="1000"
DataContext="{Binding MapViewModel, Source={StaticResource Locator}}"
mc:Ignorable="d">
<Grid>

    <ItemsControl ItemsSource="{Binding Markers}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button ToolTip="{Binding NameWithDescription}">
                    <Button.Template>
                        <ControlTemplate>
                            <local:Marker Margin="{Binding Margin}" />
                        </ControlTemplate>
                    </Button.Template>
                </Button>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

来自 SetMarkerData() 的数据运行良好,我可以在每个标记的 Margin 属性中看到正确的值。我的样本值为 (10,10)、(50,50)、(100,100) 等,所以它们应该都在一条直线上。相反,我得到了这个:

标记 img

我认为问题出在 Map.xaml 中,但我根本无法识别它。感谢帮助

标签: c#wpf

解决方案


推荐阅读