Skip to main content
 首页 » 编程设计

c#之图像边距行为

2024年02月23日13bluestorm

当我在运行时设置我的图像边距时,它表现得很奇怪,与我通过 xaml 代码设置它时不同。

我希望边距值为 (40, 16, 0, 0)。

当我在运行时添加它时,我的代码是这样的:

        System.Windows.Controls.Image proba = new System.Windows.Controls.Image(); 
        ImageSource imageSource = GetSlidePart(PresentationDocument.Open(path, false), 0, "rId2"); 
        proba.Source = imageSource; 
        proba.Width = 2245721 / 9525; 
        proba.Height = 2286004 / 9525; 
        proba.Margin = new Thickness(40, 16, 0, 0); 
        gridName.Children.Add(proba); 

但是,当我在xaml中添加图像时,cs中的代码是这样的:

        image1.Source = GetSlidePart(PresentationDocument.Open(path, false), 0, "rId2"); 

xaml 中的代码是这样的:

<Window x:Class="GetInfoFromPptxFile.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="720" Width="960"> 
 
<Grid Name="gridName"> 
    <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="416,20,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" /> 
    <Image Height="150" HorizontalAlignment="Left" Margin="40,16,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="200" /> 
</Grid> 
</Window> 

当我运行我的程序时,image1 正是我想要的位置,而名为 proba 的图像却不是。当我给他们相同的 margin 值时,为什么会这样?

请您参考如下方法:

那是因为您没有在 C# 中设置水平和垂直对齐方式。

尝试添加:

proba.VerticalAlignment = VerticalAlignment.Top; 
proba.HorizontalAlignment = HorizontalAlignment.Left; 

而且看起来一样。