小编Pet*_*ilt的帖子

如何通过用户的XAML动态地向UserControl添加控件?

我想创建一个包含TextBlock和StackPanel的用户控件,该控件允许用户在XAML中动态地将他/她自己的控件添加到用户控件.

以下是我的UserControl的示例XAML:

<UserControl x:Class="A1UserControlLibrary.UserControlStackPanel"
             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" 
             mc:Ignorable="d" 
             d:DesignHeight="200" d:DesignWidth="300">
    <StackPanel>
        <TextBlock Text="I want the user to be able to add any number of controls to the  StackPanel below this TextBlock."
                   FontFamily="Arial" FontSize="12" FontWeight="DemiBold" Margin="5,10,5,10" TextWrapping="Wrap"/>
        <StackPanel>
            <!-- I want the user to be able to add any number of controls here -->
        </StackPanel>
    </StackPanel>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

我希望用户能够将此用户控件嵌入到他们的XAML中,并将他们自己的控件添加到用户控件的堆栈面板中:

<uc:A1UserControl_StackPanel x:Name="MyUserControl_Test" Margin="10" Height="100">
    <Button Name="MyButton1" Content="Click" Height="30" Width="50"/>
    <Button Name="MyButton2" Content="Click" Height="30" Width="50"/>
    <Button Name="MyButton3" Content="Click" Height="30" Width="50"/>
</uc:A1UserControl_StackPanel>
Run Code Online (Sandbox Code Playgroud)

使用上述XAML执行此操作不起作用.有任何想法吗?

c# wpf xaml user-controls

5
推荐指数
1
解决办法
6023
查看次数

标签 统计

c# ×1

user-controls ×1

wpf ×1

xaml ×1