如何为堆栈面板中动态添加的用户控件设置高度?

How to set height to the dynamically added user control in stackpanel?

我们在一个 dll (Child.dll) 中有 wpf 用户控件 (UserControl.xaml)。

我们将 "Child.dll" 的引用添加到另一个应用程序 (ParentApplication)

在父应用程序中,我们有一个堆栈面板,我们必须在其中使用用户控件构造函数动态添加用户控件。

ParentApplication 包含:

MainWindow.xaml

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:fa="http://schemas.fontawesome.io/icons/" x:Class="ParentApplication.MainWindow"
        xmlns:Mvis="clr-namespace:Mvis;assembly=Mvis"
        Title="MainWindow" Height="1000" Width="1000" WindowStartupLocation="CenterScreen" WindowState="Maximized">
<Grid>
        <TabControl>
<TabItem Cursor="Hand">
                <TabItem.Header>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="ChildApplication"/>
                    </StackPanel>
                </TabItem.Header>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*"></RowDefinition>
                    </Grid.RowDefinitions>
                    <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" CanContentScroll="True" Grid.Row="0" >
                        <StackPanel x:Name="userControlPlaceHolder" Background="Blue"/>
                    </ScrollViewer>
                </Grid>
            </TabItem>
        </TabControl>
</Grid>
</Window>

所以我们在 MainWindow.xaml.cs 上这样做:

public partial class MainWindow : Window
{
        public MainWindow()
        {
            InitializeComponent();
            UserControl userControl = new UserControl();
            this.userControlPlaceHolder.Children.Add(userControl);           
        }
}

问题1:用户控件只显示在屏幕的一半高度。

**注意:我们没有设置任何高度为UserControl.xaml,也不能像userControl.Height=200那样设置高度控制高度; **

问题 2:我们在 MainWindow.xaml 中使用了滚动查看器,但是当我们调整应用程序大小时 window,垂直滚动条不显示。

删除 StackPanel 并将 UserControl 直接添加到 ScrollViewer:

<TabItem Cursor="Hand">
    <TabItem.Header>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="ChildApplication"/>
        </StackPanel>
    </TabItem.Header>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <ScrollViewer x:Name="sv" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" CanContentScroll="True" Grid.Row="0" >

        </ScrollViewer>
    </Grid>
</TabItem>

this.sv.Content = userControl;        

ScrollViewersStackPanels 不能很好地协同工作: