WindowsFormsHost布局问题

时间:2014-10-15 14:21:02

标签: c# wpf winforms windowsformshost

我使用WindowsFormsHost控件在WPF浏览器应用程序中嵌入了Windows窗体应用程序,并且窗体的大小总是有点短(大约10px)。在调试期间,我注意到表单高度和宽度比实际表单高度和宽度小10个像素。因此,我尝试通过向mainForm.WidthmainForm.Height添加10px来手动设置高度和宽度,但随后它会切断边缘并使其变得更糟。是否有不同的方法来设置实际的宽度/高度?

WindowsFormsHost windowsFormsHost = new WindowsFormsHost();
        //stackPanel.Width = mainForm.Width;
        //stackPanel.Height = mainForm.Height;
        //windowsFormsHost.Width = mainForm.Width;
        //windowsFormsHost.Height = mainForm.Height;
        mainForm.TopLevel = false;
        windowsFormsHost.Child = mainForm;
        stackPanel.Children.Add(windowsFormsHost);

以下是XAML代码:

<Page x:Class="WPFHost.Page1"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
      Title="Page1">
    <Grid>
        <StackPanel Margin="0,0,10,10" Name="stackPanel" 
           HorizontalAlignment="Left" VerticalAlignment="Top" />
    </Grid>
</Page>

截图:

实际形式:

enter image description here

如何在WPF上显示

enter image description here

1 个答案:

答案 0 :(得分:0)

我认为问题出在您的Margin上。您在边距中将其减少10px,然后增加StackpanelWindowsFormsHost的高度和宽度。但由于Margin这种手动设置的高度和宽度不会影响StackPanel,只会增加WindowsFormsHost的大小,并且会超出边缘。

我用红色标记了边距:

enter image description here

只需删除边距或将其设置为零:

<StackPanel Margin="0" Name="stackPanel" 
           HorizontalAlignment="Left" VerticalAlignment="Top" />

同时在C#中设置HeightWidth(它们现在会生效):

WindowsFormsHost windowsFormsHost = new WindowsFormsHost();

stackPanel.Width = mainForm.Width;
stackPanel.Height = mainForm.Height;

windowsFormsHost.Width = mainForm.Width;
windowsFormsHost.Height = mainForm.Height;