2013-08-22 25 views
-2

當我宣佈在XAML一個TreeView,我可以用我的選擇的控制(在這裏,一個StackPanel)是否有直接添加到它的元素:如何改變在C#中使用樹型視圖控制

<Window x:Class="WpfApplication1.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:sys="clr-namespace:System;assembly=mscorlib" 
    Title="MainWindow" Height="350" Width="525"> 
    <DockPanel Name="dockPanel1"> 
     <TreeView Name="treeView1"> 
      <TreeView.ItemTemplate> 
       <DataTemplate> 
        <StackPanel Orientation="Horizontal"> 
         <ProgressBar Height="15" Width="160" /> 
         <TextBlock Foreground="Red" Text="{Binding}"/> 
        </StackPanel> 
       </DataTemplate> 
      </TreeView.ItemTemplate> 
      <sys:String>Foo</sys:String> 
      <sys:String>Bar</sys:String> 
     </TreeView> 
    </DockPanel> 
</Window> 

從C#代碼中添加元素時,我該如何實現同樣的功能?

namespace WpfApplication5 
{ 
    public partial class MainWindow : Window 
    { 
     public MainWindow() { 
      InitializeComponent(); 
      // I want something more complex than just "Quux". 
      var item = new TreeViewItem { Header = "Quux" }; 
      treeView1.Items.Add(item); 
     } 
    } 
} 

回答

0

只要做到:)。

namespace WpfApplication5 
{ 
    public partial class MainWindow : Window 
    { 
     public MainWindow() { 
      InitializeComponent(); 

      var stackPanel = new StackPanel { Orientation = Orientation.Horizontal }; 
      stackPanel.Children.Add(new ProgressBar { Height = 15, Width = 160 }); 
      stackPanel.Children.Add(new TextBlock { Foreground = new SolidColorBrush(Colors.Red), Text = "Quux" }); 

      var item = new TreeViewItem { Header = stackPanel }; 
      treeView1.Items.Add(item); 
     } 
    } 
} 
+3

您可以在XAML做到這一點。操作過程代碼中的UI元素在WPF中並不需要也不需要。 –

+0

@HighCore我懷疑用其他方法調用for循環,在XAML中添加數百個元素會看起來很漂亮,如果可能的話......除非你的意思是應該使用數據綁定? –

+0

WPF中沒有「for」循環。有ItemsControl,DataTemplate和DataBinding。 –

1

當我宣佈在XAML一個TreeView,我可以用被立即添加到它

這無二的元素,我選擇的控制(在這裏,一個StackPanel) 所有項目,在代碼中只是做:

​​

或者

treeView1.ItemsSource = new[] 
{ 
    "One", "Two" 
}; 

除非您添加UI元素,否則將使用定義的DataTemplate

可能需要閱讀some references ...

+0

哦,我不知道你能做到這一點。但是,那麼如何獲得對剛添加的「item」的引用(稍後修改或添加子項)呢?目前我做'var myItem = new TreeViewItem {Header =「Quux」}; treeView1.Items.Add(項目); item.Items.Add( 「子項」); item.Header =「更改文本」;',但是如果我做了'int index = treeView1.Items.Add(「Quux」);'那麼添加子項到'Quux'並不改變它的文本更加困難。 –

+0

@GeorgesDupéron:在添加它之前只需存儲一個參考*,甚至不要考慮使用索引。另外,如果直接添加字符串,則不能修改它們,請使用具有屬性的類並將其綁定。 **閱讀參考**。 –

+0

我的意思是「我如何獲得剛剛添加的項目的參考?」如果我保留對「Text」的引用,那麼它將引用字符串「Text」,而不是對由'.Items.Add()'奇蹟般創建的'TreeViewItem'的引用。我想獲得對由'.Items.Add(「Text」)創建的「東西」的引用,但該方法的返回類型是「int」,而不是「TreeViewItem」。 –

相關問題