您可以將任何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>
來源
2017-09-14 14:55:05
mm8
謝謝.. :) 你能告訴我怎麼做,在MVVM的任期? – jclstefan
您不會在視圖中的任何位置創建控件......也許您應該查看ItemsControl的工作方式。 – mm8