2009-06-10 83 views
10

我想在一个WPF用户控件来包装一个Windows窗体控件WPF WindowsFormsHost浆纱

<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并基本消失。然后用户需要调整窗口大小(因为用户控件说我不需要空间,所以缩小了窗口大小,谢谢)。当用户调整大小时,它会延伸到用户指定的任何地方。

所以我的问题是我做错了什么?我如何让我的用户控件获得所有可用空间而不是不要求任何?

回答

3

我有同样的问题。我修正它的方式是在运行时改变WindowsFormsHost中控件的大小。

在我的情况下,我用一个StackPanel托管控件,并在运行时将我的WindowsFormsHost中的控件的高度和宽度设置为Stackpanel的高度和宽度。您想要使用ActualHieight和ActualWidth属性。

不幸的是,每次窗口大小调整时,我都必须调整大小调整事件。

19

我找到了更好的答案。

使用带有LastChildFill = true的dockPanel,然后放入带有水平和垂直对齐的WindowsFormsHost到Strech中,当然必须填写WindowsForms控件。

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

享受”,

2

我有某种类似的问题的。我能够通过从winForm窗体中删除最小和最大高度和宽度设置来解决我的问题。

之后,我用DockPanel像ykatchou建议。我仍然与DPI有一些问题,但我认为他们不会太重要。这是丑陋的,但它的工作

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 2012-05-29 15:59:39

4

一些更正:DockPanel默认启用LastChildFill,水平和垂直对齐也会自动设置为伸展。

所以简洁的答案是:使用DockPanel中

<DockPanel> 
    <WindowsFormsHost> 
    </WindowsFormsHost> 
</DockPanel>