2017-09-14 92 views
0

是否可以這樣做?在代碼後面創建控件並將它們傳遞給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中?

回答

0

您可以將任何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> 
+0

謝謝.. :) 你能告訴我怎麼做,在MVVM的任期? – jclstefan

+0

您不會在視圖中的任何位置創建控件......也許您應該查看ItemsControl的工作方式。 – mm8

相關問題