我向您展示了我在 MVVM 项目中对 2 个类所做的事情。警告:要了解您需要了解 MVVM(模型视图视图模型)范例的示例。
这些是模型:
public class Region
{
public string RegionName { get; set; }
public ObservableCollection<Cities> ListCities { get; set; }
public Region()
{
this.ListCities = new ObservableCollection<Cities>();
}
}
public class Cities
{
public string CityCode { get; set; }
public string CityName { get; set; }
}
然后是 ViewModel 中可观察集合的声明:
private ObservableCollection<GruppoAperture> _regionGroup;
public ObservableCollection<GruppoAperture> RegionGroup
{
get { return _regionGroup; }
set
{
if (_regionGroup == value)
return;
_regionGroup= value;
RaisePropertyChanged(nameof(RegionGroup));
}
}
然后是填充树视图的函数,您可以在需要时触发它:
private void PopulateTreeView ()
{
DataTable regions = //Here you create a datatable of regions
DataTable cities = // Here you create a datatable of cities
if (regions != null && cities != null)
{
if (regions.Rows.Count > 0)
{
foreach (DataRow r in region.Rows)
{
Regions reg = new Regions();
reg.RegionName = r["regionName"].ToString();
foreach(DataRow r2 in cities.Rows) //assegno aperture
{
if (r2["regionName"].ToString() == reg.RegionName)
{
reg.ListCities.Add(new Cities()
{
CityCode = r2["cityCode"].ToString(),
CityName = r2["cityName"].ToString()
});
}
}
RegionGroup.Add(reg);
}
}
}
}
然后是 XAML 部分:
<Window x:Class="MyProject.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MyProject"
xmlns:local1="clr-namespace:MyProject.ViewModels"
xmlns:local2="clr-namespace:MyProject.Models"
mc:Ignorable="d"
Title="CueModifier" Height="703.448" Width="829.25">
<Window.DataContext>
<local1:RegionViewModel></local1:RegionViewModel>
</Window.DataContext>
<Grid x:Name="regiongrid" Height="538" Margin="10,124,10,0" VerticalAlignment="Top" >
<TreeView x:Name="treeViewRegions" ItemsSource="{Binding RegionGroup}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding ListCities}">
<Label Content="{Binding RegionName}"/>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate DataType="{x:Type local2:Cities}">
<Label Content="{Binding CityName}"/>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>