WPF WindowsFormsHost sizing
我想将Windows窗体控件包装在wpf UserControl
中
1 2 3 4 5 6 7 8 9 10 11 | <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> |
请注意,高度和宽度是自动的。
当我将其放置在堆栈面板或网格控件中时,它将其高度设置为0,并且基本上消失了。然后要求用户调整窗口的大小(缩小,因为用户控件说我不需要任何空间,谢谢)。当用户调整大小时,它会扩展到用户指定的大小。
所以我的问题是我做错了什么?如何使我的用户控件占用所有可用空间,而不是不要求任何空间?
我找到了一个更好的答案。
使用带有LastChildFill = true的dockPanel,然后将其与Strech进行水平和垂直对齐,将其放入WindowsFormsHost中,当然WindowsForms控件必须填充。
1 2 3 4 5 | <DockPanel LastChildFill="true"> <WindowsFormsHost HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <Panel Dock=Fill /> </WindowsFormsHost> </DockPanel> |
享受',
一些更正:DockPanel默认情况下启用了LastChildFill,并且水平和垂直路线也自动设置为拉伸。
因此,简洁的答案是:使用DockPanel
1 2 3 4 | <DockPanel> <WindowsFormsHost> </WindowsFormsHost> </DockPanel> |
这里是同样的问题。我所做的是将WindowsForm控件(必须嵌入)的尺寸绑定到父级Host(即WindowsFormHost)的尺寸(宽度和高度),请参见下面的代码。这是在Windows窗体加载后完成的:
1 2 3 4 5 6 | private void Window_Loaded(object sender, RoutedEventArgs e) { UserWinFormControl.Height = UserWinFormControl.Parent.Height; UserWinFormControl.Width = UserWinFormControl.Parent.Width; } |
其中的UserWinFormControl是要由WindowsFormHost嵌入/托管的控件
在Xaml中写:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <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> |
一切正常,调整应用程序大小时没有闪烁。
我有同样的问题。我修复它的方法是在运行时更改WindowsFormsHost内部控件的大小。
在我的情况下,我使用StackPanel来承载控件,并在运行时将WindowsFormsHost中控件的高度和宽度设置为Stackpanel的高度和宽度。您要使用ActualHieight和ActualWidth属性。
不幸的是,每次窗口调整大小时,我都不得不调整大小事件。
我有类似的问题。我可以通过从winForm表单中删除最小和最大高度和宽度设置来解决我的问题。
之后,我按照ykatchou的建议使用了DockPanel。 DPI仍然存在一些问题,但我认为它们不会有太大关系。很难看,但是可以正常工作