當我宣佈在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);
}
}
}
您可以在XAML做到這一點。操作過程代碼中的UI元素在WPF中並不需要也不需要。 –
@HighCore我懷疑用其他方法調用for循環,在XAML中添加數百個元素會看起來很漂亮,如果可能的話......除非你的意思是應該使用數據綁定? –
WPF中沒有「for」循環。有ItemsControl,DataTemplate和DataBinding。 –