天天看点

wpf ListBox联动

和大家分享一个Listbox联动的小例子。原理很简单,关键是理解 IsSynchronizedWithCurrentItem="True" 和Binding中

path=/ 的应用,IsSynchronizedWithCurrentItem="ture"表示 同步当前选择项CurrentItem,path=/表示绑定到集合中的当前选择项,所以当它们俩配合的时候就可以实现联动的效果。具体代码如下:

<StackPanel Orientation="Horizontal">
            <ListBox Width="100" ItemsSource="{Binding}" DisplayMemberPath="Name"
                     IsSynchronizedWithCurrentItem="True">
                
            </ListBox>
            <ListBox Width="100" ItemsSource="{Binding Path=/Porvinces}" DisplayMemberPath="Name"
                     IsSynchronizedWithCurrentItem="True">
                
            </ListBox>
            <ListBox Width="100" ItemsSource="{Binding Path=/Porvinces/Cities}" DisplayMemberPath="Name"
                     IsSynchronizedWithCurrentItem="True">
                
            </ListBox>
        </StackPanel>
           
/// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public ObservableCollection<Country> country = new ObservableCollection<Country>();

        public MainWindow()
        {
            InitializeComponent();

            Country c1 = new Country() { Name = "中国", Porvinces = new List<Province>() { new Province() { Name = "辽宁", Cities = new List<City>() { new City() { Name = "大连" }, new City() { Name = "铁岭" } } },
            new Province() { Name = "河北", Cities = new List<City>() { new City() { Name = "石家庄" }, new City() { Name = "衡水" } } }}
            };
            Country c2 = new Country()
            {
                Name = "中国1",
                Porvinces = new List<Province>() { new Province() { Name = "辽宁1", Cities = new List<City>() { new City() { Name = "大连1" }, new City() { Name = "铁岭1" } } },
            new Province() { Name = "河北1", Cities = new List<City>() { new City() { Name = "石家庄1" }, new City() { Name = "衡水1" } } }}
            };

            country.Add(c1);
            country.Add(c2);

            this.DataContext = country;
        }

        
    }

    public class Country
    {
        public string Name { get; set; }
        public List<Province> Porvinces { get; set; }
    }

    public class Province
    {
        public string Name { get; set; }
        public List<City> Cities { get; set; }
    }

    public class City
    {
        public string Name { get; set; }
    }
           

联动效果就这样实现了

继续阅读