使用 WPF 时,数据绑定是您最好的朋友。只需将ItemsSource
列表框与树视图的选定项的某些集合属性绑定即可。
更新。
这是完整的示例(只需创建 WPF 应用程序项目)。模型:
public class MailFolder
{
public string Name { get; set; }
public ObservableCollection<MailItem> Items
{
get
{
return items ?? (items = new ObservableCollection<MailItem>());
}
}
private ObservableCollection<MailItem> items;
public ObservableCollection<MailFolder> SubFolders
{
get
{
return subFolders ?? (subFolders = new ObservableCollection<MailFolder>());
}
}
private ObservableCollection<MailFolder> subFolders;
}
public class MailItem
{
public string Subject { get; set; }
}
XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TreeView x:Name="MailTreeView" ItemsSource="{Binding}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:MailFolder}" ItemsSource="{Binding SubFolders}">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
<ListBox Grid.Column="1" ItemsSource="{Binding Path=SelectedItem.Items, ElementName=MailTreeView}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type local:MailItem}">
<TextBlock Text="{Binding Subject}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
这是数据上下文设置:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new[]
{
new MailFolder
{
Name = "Prejeto",
SubFolders =
{
new MailFolder
{
Name = "Prebrano",
Items =
{
new MailItem { Subject = "A" },
new MailItem { Subject = "B" },
new MailItem { Subject = "C" },
}
},
new MailFolder
{
Name = "Neprebrano",
Items =
{
new MailItem { Subject = "D" },
new MailItem { Subject = "E" },
}
},
},
Items =
{
new MailItem { Subject = "M" },
new MailItem { Subject = "N" },
}
},
new MailFolder
{
Name = "Poslano",
Items =
{
new MailItem { Subject = "F" },
new MailItem { Subject = "G" },
}
},
new MailFolder
{
Name = "Osnutki",
Items =
{
new MailItem { Subject = "H" },
}
},
new MailFolder
{
Name = "Izbrisano",
Items =
{
new MailItem { Subject = "I" },
new MailItem { Subject = "J" },
new MailItem { Subject = "K" },
}
},
new MailFolder
{
Name = "Nezaželeno",
Items =
{
new MailItem { Subject = "L" },
}
}
};
}
}
请注意,如果要反映对模型类的属性所做的更改,则需要实现INotifyPropertyChanged接口。