WPF WindowsFormsHost的大小调整

17

我想在一个 WPF UserControl 中包装一个 Windows Forms 控件。

<UserControl x:Class="MVVMLibrary.ReportViewer"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ws="clr-namespace:Microsoft.Reporting.WinForms;assembly=Microsoft.ReportViewer.WinForms"
    Height="Auto" Width="Auto">
    <Grid>
        <WindowsFormsHost Name="Host">
            <ws:ReportViewer/>
        </WindowsFormsHost>
    </Grid>
</UserControl>

请注意,Height和Width是自动的。

当我把它放在stackpanel或grid控件中时,它会将其高度设置为0并基本上消失。然后用户需要调整窗口大小(因为用户控件说我不需要空间,谢谢)。当用户调整大小时,它会拉伸到用户指定的任何大小。

我的问题是:我做错了什么?如何使我的用户控件占用所有可用空间而不是不要求任何空间?

5个回答

21

我找到了一个更好的答案。

使用具有LastChildFill=true属性的dockPanel,然后将WindowsFormsHost放在其中,使用水平和垂直对齐方式设置为Strech,当然,WindowsForms控件必须填充。

<DockPanel LastChildFill="true">
    <WindowsFormsHost HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
        <Panel Dock=Fill />
    </WindowsFormsHost>
</DockPanel>

享受吧',


6
一些更正:DockPanel默认启用LastChildFill,并且水平和垂直对齐也会自动设置为拉伸。
所以简洁的答案是:使用DockPanel。
<DockPanel>
     <WindowsFormsHost>
     </WindowsFormsHost>
</DockPanel>

4

我也遇到了同样的问题。我的解决方法是将必须嵌入的WindowsForm控件的尺寸绑定到父级宿主(即WindowsFormHost)的尺寸(宽度和高度)上,代码如下所示。这是在Windows表单加载后完成的:

 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
    UserWinFormControl.Height = UserWinFormControl.Parent.Height;
    UserWinFormControl.Width = UserWinFormControl.Parent.Width;

 }   

当 UserWinFormControl 是要由 WindowsFormHost 嵌入/托管的控件时,在 Xaml 中书写:

<Window x:Class="myAppWpf.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:WinForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
        Title="MyApp" 
        Height="737" 
        Width="1024"
        WindowStartupLocation="CenterScreen" 
        Loaded="Window_Loaded">
        <......>
        <DockPanel LastChildFill="true">
                        <WindowsFormsHost Name="windowsFormsHost1"DockPanel.Dock="Top" 
                                          Background="Yellow"         
                                          HorizontalAlignment="Stretch"             
                                          VerticalAlignment="Stretch" >
                         </WindowsFormsHost>
        </DockPanel>
        </....>
</Window>

一切正常,调整应用程序大小时没有闪烁。


1
谢谢 - 不知何故,给控件设置背景颜色显著减少了控件的闪烁。 - Justin

3

我曾经遇到过同样的问题。解决方法是在运行时更改WindowsFormsHost内部控件的大小。

在我的情况下,我使用了StackPanel来承载控件,并在运行时将控件的高度和宽度设置为Stackpanel的高度和宽度。您需要使用ActualHieight和ActualWidth属性。

不幸的是,我不得不连接到调整大小事件并在每次窗口调整大小时更改它。


2

我曾经遇到类似的问题。我通过从winForm表单中删除最小和最大高度和宽度设置来解决了我的问题。

之后,我像ykatchou建议的那样使用了DockPanel。我仍然有一些DPI方面的问题,但我认为它们不会太重要。虽然不太美观,但它能正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接