简体   繁体   English

在代码后面创建控件并将它们传递给xaml

[英]Creating controls in code behind and passing them to xaml

Is it possible to do something like this? 有可能做这样的事情吗?

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;
}

And how can I put that in XAML? 以及如何将其放入XAML?

You can add any UIElement to the Children property of a Panel that you define in your XAML markup. 您可以将任何UIElement添加到在XAML标记中定义的PanelChildren属性中。

Please refer to the following sample code. 请参考以下示例代码。

Code: 码:

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: 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM