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

C# 如何更改C中TreeViewItem使用的控件#,c#,wpf,treeview,C#,Wpf,Treeview,当我在XAML中声明TreeView时,我可以使用我选择的控件(这里是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:sy

当我在
XAML
中声明
TreeView
时,我可以使用我选择的控件(这里是
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>
就这么做吧:)

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

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

treeView1.Items.Add("Text");

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


可能需要阅读…

您可以在XAML中执行此操作。WPF中不需要也不希望在过程代码中操作UI元素。@HighCore我怀疑,如果可能的话,在XAML中添加数百个元素并调用其他方法来编写for循环会很好看。。。除非你的意思是应该使用数据绑定?WPF中没有“for”循环。有
ItemsControl
s、
DataTemplate
s和
DataBinding
。哦,我不知道你能这么做。但是,您如何获得对刚刚添加的
项的引用(稍后修改它或添加子项)?目前我做
var myItem=newtreeviewitem{Header=“qux”};树视图1.项目。添加(项目);项目。项目。添加(“子项目”);item.Header=“更改文本”,但如果我改为
int index=treeView1.Items.Add(“Quux”)
那么将子项添加到
Quux
或更改其文本就更困难了。@GeorgesDupéron:只需在添加之前存储一个引用,甚至不要考虑使用索引。另外,如果直接添加字符串,则不能修改它们,请使用具有属性的类并绑定这些属性。阅读引用。我的意思是“如何获得对刚刚添加的项的引用?”如果我保留对
“Text”
的引用,那么它将是对字符串
“Text”
的引用,而不是对由
.Items.Add()
神奇地创建的
树视图项的引用。我想获取由
.Items.Add(“Text”)
创建的“thing”的引用,但是该方法的返回类型是
int
,而不是
TreeViewItem
@GeorgesDupéron:重新考虑您的设计,通常不需要对
TreeViewItem
的引用。如果需要修改项目的某些方面,请创建相应的属性并将它们绑定到
ItemContainerStyle
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);
        }
    }
}
treeView1.Items.Add("Text");
treeView1.ItemsSource = new[]
{
    "One", "Two"
};