在代码隐藏中创建控件并将它们传递给 xaml

Creating controls in code behind and passing them to xaml

是否可以这样做?

public CONTROL selectedControl(string sControl)
{
    CONTROL result = new CONTROL();

    if(sContro.Equals("TextBox"))
    {
        TextBox txtBx = new TextBox();
        // custom TextBox
        result = txtBx;
    }
    else if(sControl.Equals("Button"))
    {
       ...
    }
    return result;
}

我怎样才能把它放在 XAML 中?

您可以将任何 UIElement 添加到您在 XAML 标记中定义的 PanelChildren 属性。

请参考以下示例代码。

代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        var child = selectedControl("TextBox");
        stackPanel.Children.Add(child);
    }

    public UIElement selectedControl(string sControl)
    {
        UIElement result = null;

        if (sControl.Equals("TextBox"))
        {
            TextBox txtBx = new TextBox();
            // custom TextBox
            result = txtBx;
        }
        //...
        return result;
    }
}

XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="300">
    <StackPanel x:Name="stackPanel">

    </StackPanel>
</Window>