在代码后面创建控件并将它们传递给xaml
问题描述:
是否可以这样做?在代码后面创建控件并将它们传递给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标记中定义的Panel
的Children
属性。
请参考以下示例代码。
代码:
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>
谢谢.. :) 你能告诉我怎么做,在MVVM的任期? – jclstefan
您不会在视图中的任何位置创建控件......也许您应该查看ItemsControl的工作方式。 – mm8