2018-8-10-WPF-省市县3级联动

网友投稿 255 2022-09-28

2018-8-10-WPF-省市县3级联动

title

author

date

CreateTime

categories


WPF 省市县3级联动



lindexi



2018-08-10 19:16:53 +0800



2018-2-13 17:23:3 +0800



WPF


本文告诉大家如何使用绑定做省市县3级联动,代码从网上找的。

首先定义显示的类,包括 id 和 名称

public class CodeView { public string Id { get; set; } public string Name { get; set; } }

然后定义省市县的数据

public class Province: CodeView { public List Child { get; set; } } public class City: CodeView { public List Child { get; set; } } public class County:CodeView { }

因为可以通过 xaml 绑定 选择的元素,所以可以绑定选择的列

请看前台代码,最重要的是通过省选择的元素来作为下一级的数据,于是选择第一个修改时,就会自动联动

可以看到​​ItemsSource="{Binding Path=SelectedItem.Child,ElementName=ComboBoxProvince}"​​绑定了上一级选择的元素,所以就可以联动。

DisplayMemberPath 就是显示的值,所以就可以显示列表是城市的名称。

后台代码需要定义几个属性

public partial class AreaSelect : UserControl, INotifyPropertyChanged { private IList _provinces = new List(); public static readonly DependencyProperty ProvinceProperty = DependencyProperty.Register("Province", typeof(string), typeof(AreaSelect), new FrameworkPropertyMetadata(string.Empty)); public static readonly DependencyProperty CityProperty = DependencyProperty.Register("City", typeof(string), typeof(AreaSelect), new FrameworkPropertyMetadata(string.Empty)); public static readonly DependencyProperty CountyProperty = DependencyProperty.Register("County", typeof(string), typeof(AreaSelect), new FrameworkPropertyMetadata(string.Empty)); public IList Provinces { get { return _provinces; } set { _provinces.Clear(); if (value != null) { foreach (Province province in value) { _provinces.Add(province); } } } } public AreaSelect() { InitializeComponent(); this.Content.DataContext = this; this.PropertyChanged += SelectedArea_PropertyChanged; } private void SelectedArea_PropertyChanged(object sender, PropertyChangedEventArgs e) { Console.WriteLine(Province + " " + City + " " + County); } private string _province; private string _city; private string _county; public string Province { get { return _province; } set { _province = value; _city = string.Empty; if (PropertyChanged != null) { PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Province")); } } } public string City { get { return _city; } set { _city = value; _county = string.Empty; if (PropertyChanged != null) { PropertyChanged.Invoke(this, new PropertyChangedEventArgs("City")); } } } public string County { get { return _county; } set { _county = value; if (PropertyChanged != null) { PropertyChanged.Invoke(this, new PropertyChangedEventArgs("County")); } } } public event PropertyChangedEventHandler PropertyChanged; }

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java中PrintWriter使用方法介绍
下一篇:2019-10-7-dotnet-Framework-源代码-·-ScrollViewer
相关文章

 发表评论

暂时没有评论,来抢沙发吧~