2011-02-14 109 views
29

我習慣於Windows窗體,但不適用於WPF。因爲我認爲WPF有很大的優勢,所以我試圖在我的新項目中使用它。WPF:從代碼添加控件

我的問題是下一個: 我有一個XML文件巫婆告訴我,我一定要添加到表單控件,但這個XML可以改變,所以我需要:

  1. 讀取XML文件(解決,沒問題)
  2. 用我讀過的數據創建一個自定義的WPF表單。

可能嗎?或者我應該使用Windows窗體?

回答

58

是的這是可能的。

WPF提供了幾種在Xaml或代碼中創建控件的方法。

對於您的情況,如果您需要動態創建控件,則必須在代碼中創建它們。您可以直接創建使用它們的構造你的控制,如:

 // Create a button. 
     Button myButton= new Button(); 
     // Set properties. 
     myButton.Content = "Click Me!"; 

     // Add created button to a previously created container. 
     myStackPanel.Children.Add(myButton); 

或者你可以創建你的控件作爲一個字符串包含XAML和使用XamlReader來解析字符串,並創建所需的控制:

 // Create a stringBuilder 
     StringBuilder sb = new StringBuilder(); 

     // use xaml to declare a button as string containing xaml 
     sb.Append(@"<Button xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' 
          xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' "); 
     sb.Append(@"Content='Click Me!' />"); 

     // Create a button using a XamlReader 
     Button myButton = (Button)XamlReader.Parse(sb.ToString()); 

     // Add created button to previously created container. 
     stackPanel.Children.Add(myButton); 

現在你想要使用的兩種方法中的哪一種真的取決於你。

讓 - 路易·

+0

謝謝!這正是我正在尋找的! – 2012-01-01 07:08:46

4

您可以通過wpf中的代碼輕鬆添加控件,您可以follow this article。值得注意的另一件事是,XAML是一種XML形式,因此您可以將XAML保存爲XML文件,這樣您就不需要在代碼中添加控件,但這取決於應用程序的複雜性。

1

我非常新的XAML但要加吉恩 - 路易斯的答案,如果你不想命名空間添加到每個元素的字符串,那麼你可以使用System.Windows做這樣的事.Markup命名空間:

   ParserContext context = new ParserContext(); 
      context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); 
      context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml"); 

      string xaml = String.Format(@"<ListBoxItem Name='Item{0}' Content='{1}' />", itemID, listItems[itemID]); 
      UIElement element = (UIElement)XamlReader.Parse(xaml, context); 

      listBoxElement.Items.Add(element); 
1

通過Children.Add方法添加控件是我找到的最快捷方式,例如

  this.Grid.Add(new TextBox() { Text = "Babau" });