当我在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);
}
}
}
答案 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);
}
}
}