我有一个UserControl,空StackPanel,如下所示。
<Grid>
<StackPanel x:Name="datawrapper" Orientation="Horizontal" Background="Yellow"/>
</Grid>
主窗口的XAML如下所示。
<ScrollViewer Grid.Row="2" Grid.Column="0" Background="Gray">
<StackPanel x:Name="holderpanel" Orientation="Vertical"/>
</ScrollViewer>
我想通过编程将数据包装器从主窗口的代码后面放入holderpanel。如果数据包装器中有控件,则将dadawrapper插入支架面板。但是,如果StackPanel为空,则从不插入。如何做到这一点?
为了帮助您澄清问题,我将提供一个您所要求的示例:
<Grid>
<ScrollViewer Grid.Row="2" Grid.Column="0" Background="Gray">
<StackPanel x:Name="holderpanel" Orientation="Vertical"/>
</ScrollViewer>
<Grid>
<StackPanel x:Name="datawrapper" Orientation="Horizontal" Background="Yellow">
<TextBlock Text="Test"/>
</StackPanel>
</Grid>
</Grid>
codeehind(对于这个例子,我添加到Loaded事件处理程序中,但它可以在其他地方使用(:
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
if (datawrapper.Children.Count > 0)
{
var grid = datawrapper.Parent as Grid;
grid.Children.Remove(datawrapper);
holderpanel.Children.Add(datawrapper);
}
}
数据包装器应该是分开的用户控件和空的,如下所示。
<Grid>
<StackPanel x:Name="datawrapper" Orientation="Horizontal" Background="Yellow"/>
</Grid>
稍后我将在数据包装器中水平添加另一个用户控件5。该用户控件如下所示。
<UserControl x:Class="WpfTest.ResultItem"
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"
xmlns:local="clr-namespace:WpfTest"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid x:Name="resultitem">
<Border CornerRadius="5" BorderBrush="#e0e0e0" Background="White" BorderThickness="2" DockPanel.Dock="Top" Margin="10 10 10 15">
<Grid Margin="0 30 0 30" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="Chart#" Width="Auto" Height="30" Margin="5 5 0 5" FontSize="20" VerticalAlignment="Center"></TextBlock>
<TextBlock Grid.Row="1" Grid.Column="0" Text="Patient Name" Width="Auto" Height="Auto" Margin="5 5 0 5" FontSize="20" VerticalAlignment="Center"></TextBlock>
<TextBlock Grid.Row="2" Grid.Column="0" Text="Home Phone#" Width="Auto" Height="Auto" Margin="5 5 0 5" FontSize="20" VerticalAlignment="Center"></TextBlock>
<TextBlock Grid.Row="3" Grid.Column="0" Text="Cell Phone#" Width="Auto" Height="Auto" Margin="5 5 0 5" FontSize="20" VerticalAlignment="Center"></TextBlock>
<TextBlock Grid.Row="4" Grid.Column="0" Text="Patient Type" Width="Auto" Height="Auto" Margin="5 5 0 5" FontSize="20" VerticalAlignment="Center"></TextBlock>
</Grid>
</Border>
</Grid>
如果数据包装器中填充了5个ResultItems,则数据包装器将垂直添加到holder面板中。