如何在C#中更改TreeViewItem使用的控件

时间:2013-08-22 19:04:53

标签: c# wpf treeview

当我在TreeView中声明XAML时,我可以使用我选择的控件(此处为StackPanel)来显示立即添加的元素:

<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);
        }
    }
}

2 个答案:

答案 0 :(得分:1)

  

当我在XAML中声明一个TreeView时,我可以使用我选择的控件(这里是一个StackPanel)来立即添加到它的元素

这适用于所有项目,只需执行以下操作:

treeView1.Items.Add("Text");

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

除非您添加UI元素,否则将使用定义的DataTemplate

可能想要阅读some references ...

答案 1 :(得分: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);
        }
    }
}