c# - WindowsFormsHost 布局问题

标签 c# wpf winforms windowsformshost

我使用 WindowsFormsHost 控件在 WPF 浏览器应用程序中嵌入了一个 Windows 窗体应用程序,但窗体的大小总是有点短(大约 10 像素)。在调试过程中,我注意到表单的高度和宽度比实际表单的高度和宽度小 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

最佳答案

我认为问题出在您的 Margin 上。您将边距减少 10 像素,然后增加 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;

关于c# - WindowsFormsHost 布局问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26384939/

相关文章:

c# - ML.NET CategoricalOneHotVectorizer 是否也对测试数据进行编码?

c# - 为什么在 C# 中没有用于 8 位和 16 位整数的算术运算符 (+,-,*,/,%)?

c# - 在 ViewModelLocator 中注册所有 View 模型和服务

.net - 这是在没有默认退出按钮的情况下关闭 prism 应用程序的正确方法吗?

c# - 我怎样才能在 WinForms 应用程序中捕获所有 'unhandled' 异常?

c# - 如何在 C# 中使用 Windows 搜索服务

C#,如何隐藏一种形式并显示另一种形式?

wpf - 具有记录和播放功能的基于 Windows 的 WPF 应用程序的 UI 自动化工具

wpf - 转换器参数绑定(bind)到 viewmodel 属性

c# - 防止数据绑定(bind) DataGridView 在编辑时进行排序