不好意思哈,刚刚看错题目了{:soso_e110:}!这是我这样实现的省市选择,感觉蛮简单的!希望对你有帮助!{:soso_e113:}
<Window x:Class="ADONET基础.CitySelectWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="省市浏览" Height="400" Width="600" Background="#FF49CD35"
BorderBrush="#FF306C27" Foreground="#FF872424" WindowStartupLocation="CenterScreen" ResizeMode="CanMinimize">
<Grid>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<ListBox DisplayMemberPath="AreaName" Name="lbPro" Height="300" Width="150" Loaded="lbPro_Loaded" SelectionChanged="lbPro_SelectionChanged"></ListBox>
<ListBox DisplayMemberPath="AreaName" Name="lbCity" Height="300" Width="150" SelectionChanged="lbCity_SelectionChanged"/>
<ListBox DisplayMemberPath="AreaName" Name="lbxian" Height="300" Width="150"></ListBox>
</StackPanel>
</Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Shapes;
namespace ADONET基础
{
/// <summary>
/// CitySelectWindow.xaml 的交互逻辑
/// </summary>
public partial class CitySelectWindow : Window
{
public CitySelectWindow()
{
InitializeComponent();
}
bool temp = true;
private void lbPro_Loaded(object sender, RoutedEventArgs e)
{
DataTable table = SqlHelper.ExecuteDataTable("select * from AreaFull");
List<Area> listPro = new List<Area>();
foreach (DataRow dataRow in table.Rows)
{
Area area = new Area();
area.AreaId=(int)dataRow["AreaId"];
area.AreaName=(string)dataRow["AreaName"];
listPro.Add(area);
}
lbPro.ItemsSource = listPro;
}
private List<Area> show(Area selectArea)
{
DataTable table = SqlHelper.ExecuteDataTable("select * from AreaFull where AreaPid=@pid", new SqlParameter("@pid", selectArea.AreaId));
List<Area> list = new List<Area>();
foreach (DataRow dataRow in table.Rows)
{
Area area = new Area();
area.AreaId = (int)dataRow["AreaId"];
area.AreaName = (string)dataRow["AreaName"];
list.Add(area);
}
return list;
}
private void lbPro_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Area selectArea = (Area)lbPro.SelectedItem;
List<Area> listCity = show(selectArea);
if (lbxian.ItemsSource != null)
{
temp = false;//这个很重要,如果lbXian已经没有对象了,就不要再让temp标记为false了
lbxian.ItemsSource = null;
}
lbCity.ItemsSource = listCity;
}
private void lbCity_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (temp)
{
Area selectArea = (Area)lbCity.SelectedItem;
List<Area> listXian = show(selectArea);
lbxian.ItemsSource = listXian;
}
else
{
temp = true;
}
}
}
}
|