主要思路:
把省的ItemsSource绑定DataContext,然后给市的ItemsSource绑定到Element(省)的SelectedItem上
xaml
<Window x:Class="Demo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" DataContext="{Binding}">
<Grid>
<TextBlock Height="23" HorizontalAlignment="Left" Margin="27,41,0,0" Name="textBlock1" Text="省" VerticalAlignment="Top" />
<ComboBox Height="23" HorizontalAlignment="Left" Margin="54,36,0,0" Name="cmbProvince" ItemsSource="{Binding}" DisplayMemberPath="Name" VerticalAlignment="Top" Width="120" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="207,36,0,0" Name="textBlock2" Text="市" VerticalAlignment="Top" />
<ComboBox Height="23" HorizontalAlignment="Left" Margin="242,36,0,0" Name="cmbCity" ItemsSource="{Binding SelectedItem.Citys, ElementName=cmbProvince}" DisplayMemberPath="Name" VerticalAlignment="Top" Width="120" />
</Grid>
</Window>
XAML
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes; namespace Demo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public List<Province> ProvinceList { set; get; }
public MainWindow()
{
InitializeComponent();
LoadData();
this.cmbProvince.DataContext = ProvinceList;
} /// <summary>
/// 构建数据
/// </summary>
public void LoadData()
{
ProvinceList = new List<Province>();
Province bj = new Province();
bj.Name = "北京"; bj.Citys = new List<City>(); City city1 = new City() { Name = "海淀" };
bj.Citys.Add(city1); city1 = new City() { Name = "朝阳" };
bj.Citys.Add(city1); city1 = new City() { Name = "西城" };
bj.Citys.Add(city1); Province sh = new Province() { Name = "上海" };
sh.Citys = new List<City>();
city1 = new City() { Name = "静安" };
sh.Citys.Add(city1); city1 = new City() { Name = "徐汇" };
sh.Citys.Add(city1); city1 = new City() { Name = "金山" };
sh.Citys.Add(city1); ProvinceList.Add(bj);
ProvinceList.Add(sh);
}
}
}
MainWindow.xaml 的交互逻辑
两个类:
namespace Demo
{
public class City
{
public string Name { get; set; } }
}
Class City
using System.Collections.Generic; namespace Demo
{
public class Province
{
public string Name { get; set; } public List<City> Citys { get; set; } }
}
Class Province